LoginSignup
22
22

More than 5 years have passed since last update.

【CakePHP】ビヘイビアの使い方

Last updated at Posted at 2014-01-21

モデル間で処理を共通化するための機能。

ビヘイビアの作成

app/Model/Behaviorに置く。
ファイル名(クラス名)は、ビヘイビア名+Behavior。例えば、UtillBehavior.php。

第一引数には呼び出し元のモデルが入る。

class UtillBehavior extends ModelBehavior {
  public function increment(Model $model,$par){
      return ($par+1);
  }
}

ビヘイビアの呼び出し方

モデルから呼び出す場合は、第一引数の$modelは省略。
ビヘイビア内から呼び出す場合は、第一引数の$modelも書く。

モデルからの呼び出し方

class User extends AppModel{
    // 使用したいビヘイビアを指定
    public $actsAs = array('Utill');

    public function incrementAge($age){
        // $this->メソッド名で呼び出す
        return $this->increment($age);
    }
}

ビヘイビア内からの呼び出し方

class UtillBehavior extends ModelBehavior {
  public function increment(Model $model,$par){
      return ($par+1);
  }

  public public hoge(Model $model,$para){
    //ビヘイビア内からビヘイビアのメソッドを呼び出す
    return $this->increment(Model $model,$par);
  }
}
22
22
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
22