Yii - 建立行為



假設我們想建立一個行為,該行為將附加其行為的元件的“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 − 要將此行為附加到 MyUser 模型,請按此方式修改它。

<?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 − 向 SiteController 新增一個 actionTestBehavior 函式。

public function actionTestBehavior() {
   //creating a new user
   $model = new MyUser();
   $model->name = "John";
   $model->email = "john@gmail.com";
   if($model->save()){
      var_dump(MyUser::find()->asArray()->all());
   }
}

步驟 4 − 在位址列中鍵入 https://:8080/index.php?r=site/test-behavior,您將看到新建立的 MyUser 模型的 name 屬性為大寫。

UppercaseBehavior
廣告