web-servicesrestyiiyii-events

Yii how to invoke an event handler on each request


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.
 }
}

Solution

  • 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
         }
    }