<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/ namespace yii\behaviors; use yii\base\InvalidCallException;
use yii\db\BaseActiveRecord; /**
* TimestampBehavior automatically fills the specified attributes with the current timestamp.
*
* To use TimestampBehavior, insert the following code to your ActiveRecord class:
*
* ```php
* use yii\behaviors\TimestampBehavior;
*
* public function behaviors()
* {
* return [
* TimestampBehavior::className(),
* ];
* }
* ```
*
* By default, TimestampBehavior will fill the `created_at` and `updated_at` attributes with the current timestamp
* when the associated AR object is being inserted; it will fill the `updated_at` attribute
* with the timestamp when the AR object is being updated. The timestamp value is obtained by `time()`.
*
* Because attribute values will be set automatically, it's a good idea to make sure `created_at` and `updated_at` aren't
* in `rules()` method of the model.
*
* For the above implementation to work with MySQL database, please declare the columns(`created_at`, `updated_at`) as int(11) for being UNIX timestamp.
*
* If your attribute names are different or you want to use a different way of calculating the timestamp,
* you may configure the [[createdAtAttribute]], [[updatedAtAttribute]] and [[value]] properties like the following:
*
* ```php
* use yii\db\Expression;
*
* public function behaviors()
* {
* return [
* [
* 'class' => TimestampBehavior::className(),
* 'createdAtAttribute' => 'create_time',
* 'updatedAtAttribute' => 'update_time',
* 'value' => new Expression('NOW()'),
* ],
* ];
* }
* ```
*
* In case you use an [[\yii\db\Expression]] object as in the example above, the attribute will not hold the timestamp value, but
* the Expression object itself after the record has been saved. If you need the value from DB afterwards you should call
* the [[\yii\db\ActiveRecord::refresh()|refresh()]] method of the record.
*
* TimestampBehavior also provides a method named [[touch()]] that allows you to assign the current
* timestamp to the specified attribute(s) and save them to the database. For example,
*
* ```php
* $model->touch('creation_time');
* ```
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @author Alexander Kochetov <creocoder@gmail.com>
* @since 2.0
*/
class TimestampBehavior extends AttributeBehavior
{
/**
* @var string the attribute that will receive timestamp value
* Set this property to false if you do not want to record the creation time.
*/
public $createdAtAttribute = 'created_at';
/**
* @var string the attribute that will receive timestamp value.
* Set this property to false if you do not want to record the update time.
*/
public $updatedAtAttribute = 'updated_at';
/**
* @inheritdoc
*
* In case, when the value is `null`, the result of the PHP function [time()](http://php.net/manual/en/function.time.php)
* will be used as value.
*/
public $value; /**
* @inheritdoc
*/
public function init()
{
parent::init(); if (empty($this->attributes)) {
$this->attributes = [
BaseActiveRecord::EVENT_BEFORE_INSERT => [$this->createdAtAttribute, $this->updatedAtAttribute],
BaseActiveRecord::EVENT_BEFORE_UPDATE => $this->updatedAtAttribute,
];
}
} /**
* @inheritdoc
*
* In case, when the [[value]] is `null`, the result of the PHP function [time()](http://php.net/manual/en/function.time.php)
* will be used as value.
*/
protected function getValue($event)
{
if ($this->value === null) {
returntime();
}
return parent::getValue($event);
} /**
* Updates a timestamp attribute to the current timestamp.
*
* ```php
* $model->touch('lastVisit');
* ```
* @param string $attribute the name of the attribute to update.
* @throws InvalidCallException if owner is a new record (since version 2.0.6).
*/
public function touch($attribute)
{
/* @var $owner BaseActiveRecord */
$owner = $this->owner;
if ($owner->getIsNewRecord()) {
throw new InvalidCallException('Updating the timestamp is not possible on a new record.');
}
$owner->updateAttributes(array_fill_keys((array) $attribute, $this->getValue(null)));
}
}

TimestampBehavior 里面的public function init(){}初始化绑定事件处理的方法数据

 /**
* @inheritdoc
*/
public function init()
{
parent::init(); if (empty($this->attributes)) {
$this->attributes = [
BaseActiveRecord::EVENT_BEFORE_INSERT => [$this->createdAtAttribute, $this->updatedAtAttribute],
BaseActiveRecord::EVENT_BEFORE_UPDATE => $this->updatedAtAttribute,
];
}
}

TimestampBehavior 父级AttributeBehavior 里面events()方法  为事件绑定执行handle :evaluateAttributes方法

 /**
* @inheritdoc
*/
public function events()
{
return array_fill_keys(
array_keys($this->attributes),
'evaluateAttributes'
);
}

事件绑定的方法:evaluateAttributes方法,

  /**
* Evaluates the attribute value and assigns it to the current attributes.
* @param Event $event
*/
public function evaluateAttributes($event)
{
if ($this->skipUpdateOnClean
&& $event->name == ActiveRecord::EVENT_BEFORE_UPDATE
&& empty($this->owner->dirtyAttributes)
) {
return;
} if (!empty($this->attributes[$event->name])) {
$attributes = (array) $this->attributes[$event->name];
$value = $this->getValue($event);
foreach ($attributes as $attribute) {
// ignore attribute names which are not string (e.g. when set by TimestampBehavior::updatedAtAttribute)
if (is_string($attribute)) {
$this->owner->$attribute = $value;
}
}
}
}

当update 或者insert  save数据时候,BaseActiveRecord.php 里面的save():

 /**
* Saves the current record.
*
* This method will call [[insert()]] when [[isNewRecord]] is true, or [[update()]]
* when [[isNewRecord]] is false.
*
* For example, to save a customer record:
*
* ```php
* $customer = new Customer; // or $customer = Customer::findOne($id);
* $customer->name = $name;
* $customer->email = $email;
* $customer->save();
* ```
*
* @param boolean $runValidation whether to perform validation (calling [[validate()]])
* before saving the record. Defaults to `true`. If the validation fails, the record
* will not be saved to the database and this method will return `false`.
* @param array $attributeNames list of attribute names that need to be saved. Defaults to null,
* meaning all attributes that are loaded from DB will be saved.
* @return boolean whether the saving succeeded (i.e. no validation errors occurred).
*/
public function save($runValidation = true, $attributeNames = null)
{
if ($this->getIsNewRecord()) {
return $this->insert($runValidation, $attributeNames);
} else {
return $this->update($runValidation, $attributeNames) !== false;
}
}

调用ActiveRecord.php 里面的insert()  和update  ():

  public function insert($runValidation = true, $attributes = null)
{
if ($runValidation && !$this->validate($attributes)) {
Yii::info('Model not inserted due to validation error.', __METHOD__);
return false;
} if (!$this->isTransactional(self::OP_INSERT)) {
return $this->insertInternal($attributes);
} $transaction = static::getDb()->beginTransaction();
try {
$result = $this->insertInternal($attributes);
if ($result === false) {
$transaction->rollBack();
} else {
$transaction->commit();
}
return $result;
} catch (\Exception $e) {
$transaction->rollBack();
throw $e;
}
}
public function update($runValidation = true, $attributeNames = null)
{
if ($runValidation && !$this->validate($attributeNames)) {
Yii::info('Model not updated due to validation error.', __METHOD__);
return false;
} if (!$this->isTransactional(self::OP_UPDATE)) {
return $this->updateInternal($attributeNames);
} $transaction = static::getDb()->beginTransaction();
try {
$result = $this->updateInternal($attributeNames);
if ($result === false) {
$transaction->rollBack();
} else {
$transaction->commit();
}
return $result;
} catch (\Exception $e) {
$transaction->rollBack();
throw $e;
}
}

调用ActiveRecord.php 里面insertInternal() 和updateInternal():

 /**
* Inserts an ActiveRecord into DB without considering transaction.
* @param array $attributes list of attributes that need to be saved. Defaults to null,
* meaning all attributes that are loaded from DB will be saved.
* @return boolean whether the record is inserted successfully.
*/
protected function insertInternal($attributes = null)
{
if (!$this->beforeSave(true)) {
return false;
}
$values = $this->getDirtyAttributes($attributes);
if (($primaryKeys = static::getDb()->schema->insert(static::tableName(), $values)) === false) {
return false;
}
foreach ($primaryKeys as $name => $value) {
$id = static::getTableSchema()->columns[$name]->phpTypecast($value);
$this->setAttribute($name, $id);
$values[$name] = $id;
} $changedAttributes = array_fill_keys(array_keys($values), null);
$this->setOldAttributes($values);
$this->afterSave(true, $changedAttributes); return true;
}
/**
* @see update()
* @param array $attributes attributes to update
* @return integer number of rows updated
* @throws StaleObjectException
*/
protected function updateInternal($attributes = null)
{
if (!$this->beforeSave(false)) {
return false;
}
$values = $this->getDirtyAttributes($attributes);
if (empty($values)) {
$this->afterSave(false, $values);
return 0;
}
$condition = $this->getOldPrimaryKey(true);
$lock = $this->optimisticLock();
if ($lock !== null) {
$values[$lock] = $this->$lock + 1;
$condition[$lock] = $this->$lock;
}
// We do not check the return value of updateAll() because it's possible
// that the UPDATE statement doesn't change anything and thus returns 0.
$rows = static::updateAll($values, $condition); if ($lock !== null && !$rows) {
throw new StaleObjectException('The object being updated is outdated.');
} if (isset($values[$lock])) {
$this->$lock = $values[$lock];
} $changedAttributes = [];
foreach ($values as $name => $value) {
$changedAttributes[$name] = isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null;
$this->_oldAttributes[$name] = $value;
}
$this->afterSave(false, $changedAttributes); return $rows;
}

调用BaseActiveRecord.php 里面的beforeSave(),触发$this->trigger($insert ? self::EVENT_BEFORE_INSERT : self::EVENT_BEFORE_UPDATE, $event)事件执行添加之前绑定的事件方法evaluateAttributes自动相关添加属性值:

  public function beforeSave($insert)
{
$event = new ModelEvent;
$this->trigger($insert ? self::EVENT_BEFORE_INSERT : self::EVENT_BEFORE_UPDATE, $event); return $event->isValid;
}
}

Yii2 TimestampBehavior行为的更多相关文章

  1. Yii2 TimestampBehavior 用来自动给指定的属性填充当前时间戳

    要使用 TimestampBehavior,把下面的代码加到你的 ActiveRecord 类中: use yii\behaviors\TimestampBehavior; public functi ...

  2. Yii2的深入学习--行为Behavior

    我们先来看下行为在 Yii2 中的使用,如下内容摘自 Yii2中文文档 行为是 [[yii\base\Behavior]] 或其子类的实例.行为,也称为 mixins,可以无须改变类继承关系即可增强一 ...

  3. Yii2框架RESTful API教程(二) - 格式化响应,授权认证和速率限制

    之前写过一篇Yii2框架RESTful API教程(一) - 快速入门,今天接着来探究一下Yii2 RESTful的格式化响应,授权认证和速率限制三个部分 一.目录结构 先列出需要改动的文件.目录如下 ...

  4. yii2 小技巧

    参考地址:http://www.cnblogs.com/sandea/p/5714830.html 1.不通过日志获取AR执行的原生SQL语句和打印变量数据 $query = User::find() ...

  5. YII2项目常用技能知识总结

    1.不通过日志获取AR执行的原生SQL语句和打印变量数据 $query = User::find() ->select(['username'])->where(['id'=>[1, ...

  6. 忘记时间戳的存在——Yii2超实用的自动更新时间戳的Behavior(改进版)

    本文改进了Yii2中内置行为类TimestampBehavior,使得时间戳字段(如created_at,updated_at) 完全自己更新,方便得让你忘记它们的存在. Yii2的内置行为类Time ...

  7. Yii2基本概念之——行为(Behavior)

    使用行为(behavior)可以在不修改现有类的情况下,对类的功能进行扩充.通过将行为绑定到一个类,可以使得类具有行为本身所具有的属性和方法,就好像是类本来就具有的这些属性和功能一样. 好的代码设计, ...

  8. Yii2 Restful api设计--App接口编程

    Yii2框架写一套RESTful风格的API,对照魏曦教你学 一,入门 一.目录结构 实现一个简单地RESTful API只需用到三个文件.目录如下: frontend ├─ config │ └ m ...

  9. Yii2框架RESTful API教程

    前不久做一个项目,是用Yii2框架写一套RESTful风格的API,就去查了下<Yii 2.0 权威指南 >,发现上面写得比较简略.所以就在这里写一篇教程贴,希望帮助刚接触Yii2框架RE ...

随机推荐

  1. 换一换js

    (function(){ var tit = $("#changes"), con = $("#wday>ul"), page = con.length, ...

  2. Unity C#写的A*寻路

    原地址:http://www.unity蛮牛.com/blog-13769-1078.html 首先看了这篇翻译外国人的文章http://www.raywenderlich.com/zh-hans/2 ...

  3. Sql狗血的Bit类型赋值与取值

    Bit 数据类型在 SQL Server 数据库中以存储 1.0 进行存储. 往数据库中添加,修改 bit 类型的字段时,只能用 0 或者 1. 关于修改 Bit 类型的字段 1.若使用 SQL 语句 ...

  4. 服务器部署_centos 安装nginx手记

    前言: a.linux上安装nginx网上有很多文章,本文仅仅是自己整理备忘. b.安装centos的时候,把develop相关组件都装上,免得缺这个缺哪个. c. 本文软件版本:nginx-1.2. ...

  5. linux 访问windows共享

    1. windows端建立一个用户user用于共享访问 2. 共享一个目录,设置user可以访问,并在windows系统中确认可以访问 3. linux端创建一个用于挂载共享目录的目录    mkdi ...

  6. sql 复杂自动编号错误批量修改方案

    [一篮饭特稀原创,转载请注明出自http://www.cnblogs.com/wanghafan/p/5133953.html]  前提:自动编号为18位,前4位是年份,中间10位是XXXX,最后四位 ...

  7. DHTMLX 前端框架 建立你的一个应用程序 教程(七)-- 添加筛选功能

    表格的过滤筛选 我们在每列第一行添加一个文本,用做数据的条件筛选. 我们还提供服务端的筛选 ,当有大量数据时 , 我们可以使用dhtmlxConnector 进行后台数据的筛选. 添加过滤器到表格列中 ...

  8. phpexcelreader超级简单使用

    phpexcelreader超级简单使用 该php类可以到官网下载:http://www.codeplex.com/PHPExcel,下载的文件不能直接使用要看下面的备注. 备注: 1.要将olere ...

  9. SPRING IN ACTION 第4版笔记-第五章Building Spring web applications-001-SpringMVC介绍

    一. 二.用Java文件配置web application 1. package spittr.config; import org.springframework.web.servlet.suppo ...

  10. ruby 模块 的引入

    module My NA="China" def My.set_name(name) @name=name end def My.get_name return @name end ...