0

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.
 }
}
Shahid Karimi
  • 4,096
  • 17
  • 62
  • 104

2 Answers2

1

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
     }
}
Rohan
  • 3,296
  • 2
  • 32
  • 35
1

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

acorncom
  • 5,975
  • 1
  • 19
  • 31