init() without using modules

Hi, I’m very new to Yii so forgive me if I’m missing the obvious.

When using modules, you have init() at your disposal, when the module loads.

In init() you have a chance to run some of your code before any of the module controllers/actions get executed.

For instance: In case of a module ‘admin’, you could use this opportunity to always check if a user is logged in or not.


When I’m not using modules, I just have a bunch of controllers.

For instance:

/news runs NewsController->actionIndex

/page runs PageController->actionIndex

Does Yii then still offer an centralized place to run code that always has to be executed, just like init() in a module?

There’s got to be a more efficient way than to place a call to this code in every controller separately?

I’ve got the feeling I’m missing something basic here.

Any pointers?

There are many ways to do so.

  1. Extending all controllers from a base one and using base’s init().

  2. Events:

Yii::app()->onBeginRequest = function($event){

    // do something


Thanks! that was quick.

Solution 1 is probably the most elegant (why didn’t I think of that myself :)

If I where to use solution 2, wouldn’t I be stuck with the same problem?

Where do i put this eventhandler so that it is always declared, regardless of the controller (brings me back to solution 1)

index.php, for example.