假设我们要创建一个行为,将行为连接到的组件的 “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 属性的值是大写。

