あなたの場合、フィルターまたはbeforeAction
メソッドのどちらかを使用する方が良いと思います。
フィルター方法:
フィルターは、コントローラー アクションの実行前および/または実行後に実行されるように構成されたコードです。
サンプル:
class SomeController extends Controller {
// ... other code ...
public function filters() {
return array(
// .. other filters ...
'mysimple', // our filter will be applied to all actions in this controller
// ... other filters ...
);
}
public function filterMysimple($filterChain) { // this is the filter code
// ... do stuff ...
$filterChain->run(); // this bit is important to let the action run
}
// ... other code ...
}
beforeAction
仕方:
このメソッドは、アクションが実行される直前 (考えられるすべてのフィルターの後) に呼び出されます。このメソッドをオーバーライドして、アクションの最後の準備を行うことができます。
サンプル:
class SomeController extends Controller {
// ... other code ...
protected function beforeAction($action) {
if (parent::beforeAction($action)){
// do stuff
return true; // this line is important to let the action continue
}
return false;
}
// ... other code ...
}
補足として、この方法でもコントローラー内の現在のアクションにアクセスできます : $this->action
、の値を取得するid
: $this->action->id
:
if($this->action->id == 'view') { // say you want to detect actionView
$this->layout = 'path/to/layout'; // say you want to set a different layout for actionView
}