行爲是 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 = '[email protected]';
$user->save();
echo $user->created_at; // 顯示當前時間戳
TimestampBehavior 行爲還提供了一個有用的方法 touch(), 這個方法能將當前時間戳賦值給指定屬性並保存到數據庫:
$user->touch('login_time');