行为是 yii\base\Behavior 或其子类的实例。 行为,也称为 mixins, 可以无须改变类继承关系即可增强一个已有的 组件 类功能。 当行为附加到组件后,它将“注入”它的方法和属性到组件, 然后可以像访问组件内定义的方法和属性一样访问它们。 此外,行为通过组件能响应被触发的事件,从而自定义或调整组件正常执行的代码。
一、行为 Behavior 相关概念
1、行为的定义,
2、行为附加
3、行为使用
4、行为移除
5、处理事件
以上官方权威指南有详细讲解,http://www.yiichina.com/doc/guide/2.0/concept-behaviors
二、使用 timeStampBehavior
这个行为支持在 Active Record 存储时自动更新它的时间戳属性
namespace app\models\User;
use yii\db\ActiveRecord;
use yii\behaviors\TimestampBehavior;
class User extends ActiveRecord
{
// ...
public function behaviors()
{
return [
[
'class' => TimestampBehavior::className(),
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
],
// if you're using datetime instead of UNIX timestamp:
// 'value' => new Expression('NOW()'),
],
];
}
}
以上指定的行为数组:
- 当记录插入时,行为将当前时间戳赋值给
created_at
和updated_at
属性; - 当记录更新时,行为将当前时间戳赋值给
updated_at
属性。
注意:For the above implementation to work with MySQL database, please declare the columns(
created_at
,updated_at
) as int(11) for being UNIX timestamp.
With that code in place, if you have a User
object and try to save it, you will find its created_at
and updated_at
are automatically filled with the current UNIX timestamp:
$user = new User;
$user->email = 'test@example.com';
$user->save();
echo $user->created_at; // 显示当前时间戳
TimestampBehavior 行为还提供了一个有用的方法 touch(), 这个方法能将当前时间戳赋值给指定属性并保存到数据库:
$user->touch('login_time');