Yii 1.1: How to use a component before every action of a controller


I guess this is a tip on how to execute some code before every action in a controller, because I will tell you how I did it and maybe you can use the idea in your project.

I needed to run some code before an action executed, but I also needed to share that code between multiple controllers (but not all), so I started by creating a Component and saving it to protected/components:

Filename: CensoConfig.php
class CensoConfig extends CApplicationComponent
        public function configurar()
            $config = array();
            if (Yii::app()->params['empresa_id'] > 0) {
                $censo_config = Parametro::model()->obtener_parametro('CENSO.CONFIG', Yii::app()->params['empresa_id']);
                if ($censo_config !== false) {
                    $config = json_decode($censo_config->parametro, true);
            Yii::app()->params['censo_config'] = $config;

Next, in my protected/config/main.php file I have these to import all my components, including CensoConfig:

// autoloading model and component classes
        ... some other files

Almost done, now use the component in as many Controllers as you need, like this:

class ConsultaController extends Controller
    protected function beforeAction($event)
        $conf = new CensoConfig;
        return true;

You can use other methods to achieve the same thing, this is not the only way or the best solution for YOUR project, but it works. Hope this is useful to someone.

Total 1 comment

#12867 report it
bluyell at 2013/04/16 08:08pm

1) why you dont use the hierarchy in Controller.php ? creating the required method in Controller, next using it in the derivated classes:

class Controller ..bla {
   private $_comp;
   public function getComp(){
     if($this->_comp == null) $this->_comp = new CensoConfig();
     return $this->_comp;
   // maybe a filter mechanism instead of beforeAction..?
   public function beforeAction($e){
      $this->comp->configurar(); // yes..comp, not _comp. using magic getter

This solution avoid the noise. Every action declared in those extended classes from this Controller.php class will be handled by its base class in a smooth way.

2) why to extend from CApplicationComponent if you are not using the component at all (as an example: Yii::app()->mycomponent->bla(); ) then a single class is sufficient.

3) did you consider filters instead of beforeAction ?

Leave a comment

Please to leave your comment.

Write new article