Yii how to invoke an event handler on each request

158 Views Asked by At

Is it possible in Yii to invoke an event handler so that it executes on each controller action call. Basically I have a RESTful application. On each request, currently, it explicitly calls an authentication function. What I want is the authentication function calls when any request is made.

What I did

class MyController extends RestController{
 public function actionDosomething(){
  $this->authenticate();// I don't want this line to be put in every controller action.
 }
}
2

There are 2 best solutions below

3
On BEST ANSWER

Your answer is the beforeAction callback. Place this in your main Controller file.

public function beforeAction($action) {

     if(in_array($action, array( /* you list of actions */ ))) 
     {
       //do your thing
     }
}
0
On

Another option (in my opinion the more Yii-like approach) is to write a filter and then apply it as desired using the filters method.

It will give you even more flexibility in the future: http://www.yiiframework.com/doc/guide/1.1/en/basics.controller#filter