Yii extensions – Where to put site-wide functions?

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(); ?>

4 thoughts on “Yii extensions – Where to put site-wide functions?

  1. either that or you can also just create a class under protected/components and then create your helper methods as static methods in that class.

    But i think your solution is better, because it promotes more reuse. I’ll use it too.

  2. For site-wide functionality, particularly when extending CApplicationComponent, it might be better to put your “Functions.php” class file in the “protected/components” directory instead of “extensions”.

    Then, your “components” array in “config/main.php” would look like this:
    ‘functions’=>array(
    ‘class’=>’application.components.Functions’,
    ),

    Cheers,
    Chad

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>