假設我們要創建一個行為,將行為連接到的組件的 “name” 屬性轉換為大寫。
第1步 - 在 components 檔夾中,創建一個 UppercaseBehavior.php 檔並使用下麵的代碼。
<?php namespace app\components; use yii\base\Behavior; use yii\db\ActiveRecord; class UppercaseBehavior extends Behavior { public function events() { return [ ActiveRecord::EVENT_BEFORE_VALIDATE => 'beforeValidate', ]; } public function beforeValidate($event) { $this->owner->name = strtoupper($this->owner->name); } } ?>
在上面的代碼中,我們創建了 UppercaseBehavior ,在觸發 “beforeValidate”事件後將 name 屬性的值大寫。
第2步 - 要附加這個行為到 models/MyUser.php 模型,修改如下代碼:
<?php namespace app\models; use app\components\UppercaseBehavior; use Yii; /** * This is the model class for table "user". * * @property integer $id * @property string $name * @property string $email */ class MyUser extends \yii\db\ActiveRecord { public function behaviors() { return [ // anonymous behavior, behavior class name only UppercaseBehavior::className(), ]; } /** * @inheritdoc */ public static function tableName() { return 'user'; } /** * @inheritdoc */ public function rules() { return [ [['name', 'email'], 'string', 'max' => 255] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'name' => 'Name', 'email' => 'Email', ]; } } ?>
現在,當我們創建或更新的用戶,它的 name 屬性將會自動轉換為大寫。
第3步 - 添加 actionTestBehavior() 函數到 SiteController。
public function actionTestBehavior() { //creating a new user $model = new MyUser(); $model->name = "zaixian"; $model->email = "xuhuhu.com@gmail.com"; if($model->save()){ var_dump(MyUser::find()->asArray()->all()); } }
第4步 - 訪問URL: http://localhost:8080/index.php?r=site/test-behavior ,會看到新創建的 MyUser 模型的 name 屬性的值是大寫。
