Yii components can be quite handy, exposing functions to the entire app. This helps keep the controller thin and adheres to the DRY methodology.
To create a “Hello World” component, first we create the component in protected/components, and populate it with:
class Hello extends CApplicationComponent
{
public function init()
{
// Any needed initialization for the component goes here
}
public function World()
{
return "Hello World!";
}
}
Now that we have our component, the next step is to modify our protected/config/main.php, including our new component in the components array:
'components'=>array(
'Hello'=>array(
'class'=>'Hello',
),
),
In the same file, we can set our component to be preloaded. Meaning it won’t be lazy loaded on first access, but rather preloaded on the app’s init.
// preloading components
'preload'=>array('log','Hello'),
Lastly, we can access the output from our component by using something like:
Yii::app()->Hello->World()
Echoing this var should display “Hello World”
//Prints "Hello World"
echo Yii::app()->Hello->World();