Yii2 TimestampBehavior行为

时间:2024-01-07 21:21:20
 <?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;
}
}