Yii Framework Forum: Yii Registry - Yii Framework Forum

Jump to content

  • (2 Pages)
  • +
  • 1
  • 2
  • You cannot start a new topic
  • This topic is locked

Yii Registry Rate Topic: ***** 1 Votes

#21 User is offline   redian 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 3
  • Joined: 23-November 10

Posted 03 August 2012 - 08:02 AM

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
0

#22 User is offline   Maurizio Domba Cerin 

  • Yii - Yesss It Is !!!
  • Yii
  • Group: Yii Dev Team
  • Posts: 4,355
  • Joined: 12-October 09
  • Location:Croatia

Posted 03 August 2012 - 08:44 AM

@redian note that you replied to a post from 2009 that is in the Yii 1.0.x section...
Find more about me.... btw. Do you know your WAN IP?
0

Share this topic:


  • (2 Pages)
  • +
  • 1
  • 2
  • You cannot start a new topic
  • This topic is locked

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users