How to use a component before every action of a controller

You are viewing revision #1 of this wiki article.
This is the latest version of this article.

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
<?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
	'import'=>array(
		... some other files
		'application.components.*',
	),

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

<?php
class ConsultaController extends Controller
{
	protected function beforeAction($event)
	{
		$conf = new CensoConfig;
		$conf->configurar();
		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.