Hello Everyone
This is how i implemented the Registry Pattern on my application.
Registry Class
<?php
// This class implements the Registry pattern, where we can save objects in a
//global library and have them accessible throughout the whole application
final class Registry extends CApplicationComponent
{
/**
* The internal class library
*
* @var array
*/
private static $library;
/**
* No need for a constructor.
*/
private final function __construct() { }
/**
* Returns an object reference from the library
*
* @param string $name
* @return object|null
*/
public static function get( $name = null )
{
self::_init();
if( empty( $name ) )
{
return null;
}
if( array_key_exists( $name, self::$library ) )
{
return self::$library[ $name ];
}
}
/**
* Sets a reference to an object in the internal library
*
* @param string $name
* @param object $obj
*/
public static function set( $name = null, $obj )
{
self::_init();
if( empty( $name ) )
{
return;
}
self::$library[ $name ] = $obj;
}
/**
* Initialize the library
*/
protected static function _init()
{
if( empty( self::$library ) )
{
self::$library = array();
}
}
}
?>
For a global object that i want it to be accessible throughout my application i do the following:
1- Add a beforeAction method on the controller to add the object i want in the library :
protected function beforeAction($action){
Registry::set('user', (Yii::app()->user->isGuest)? null : User::model()->findByPk(Yii::app()->user->id));
return parent::beforeAction($action);
}
2- Then i would have the user object available through out the application and simply check via
Registry::get('user');
Hope this helps anyone, and if someone has any ideas how to improve in this please you are more than welcome to do so.
Redian