Yii-creating-behavior

提供:Dev Guides
移動先:案内検索

Yii-ビヘイビアの作成

ビヘイビアが関連付けられているコンポーネントの「名前」プロパティを大文字にするビヘイビアを作成するとします。

ステップ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',
         ];
      }
   }
?>

これで、ユーザーを作成または更新するたびに、その名前プロパティは大文字になります。

ステップ3 *- *actionTestBehavior 関数を SiteController に追加します。

public function actionTestBehavior() {
  //creating a new user
   $model = new MyUser();
   $model->name = "John";
   $model->email = "[email protected]";
   if($model->save()){
      var_dump(MyUser::find()->asArray()->all());
   }
}

ステップ4 *-アドレスバーに *http://localhost:8080/index.php?r = site/test-behavior と入力すると、新しく作成された MyUser モデルの name プロパティが含まれていることがわかります。大文字。

UppercaseBehavior