我認(rèn)為這是一個(gè)在所有控制器的動(dòng)作之前執(zhí)行一些代碼的小技巧, 我將告訴你如何去做, 你可能會(huì)在你的項(xiàng)目中用到它.
我需要在一個(gè)動(dòng)作前執(zhí)行一段代碼, 但我同樣也需要在其他的控制器(不是所有控制器)中執(zhí)行, 所以我在 protected/components
下創(chuàng)建了一個(gè)組件:
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;
}
}
下一步,在 protected/config/main.php
文件中引入所有組件,包括 CensoConfig
:
// autoloading model and component classes
'import'=>array(
... some other files
'application.components.*',
),
差不多完成了, 在需要使用組件的控制器中使用如下代碼:
<?php
class ConsultaController extends Controller
{
protected function beforeAction($event)
{
$conf = new CensoConfig;
$conf->configurar();
return true;
}
你可以使用其他方法達(dá)到相同的效果,對(duì)你的項(xiàng)目來說, 這不是唯一的方法,也不是最好的方法,但它可以達(dá)到效果,希望它對(duì)你有用.
[英文原文/ How to use a component before every action of a controller]