One aspect of Yii that’s confused me in the past is where to put generic site-wide functions that you want to access throughout the application. Stuff like an encryption method or a hash generator, that don’t belong to a specific model.
The answer, of course, is to use Yii’s system of Extensions. Some reading through the documentation (http://www.yiiframework.com/doc/guide/1.1/en/extension.create) revealed that what I was looking for was an ‘Application component’ which extends Yii’s existing CApplicationComponent and is then available using
Yii::app()->yourExtension->yourMethod();
Firstly, create a new directory within protected/extensions called ‘functions’.
Then, in there, create a new php file called ‘Functions.php’
This file is your extension class, but it must extend CApplicationComponent:
<?php
class Functions extends CApplicationComponent
{
public function returnSomething()
{
return 'Something';
}
}
?>
Now go to protected/config/main.php and add the reference to your class in the ‘components’ array:
'components'=>array(
'functions'=>array(
'class'=>'application.extensions.functions.Functions',
),
),
Now, all being well you can access your functions using:
<?php
print Yii::app()->functions->returnSomething();
?>