View Single Post
Old 01-20-2008, 12:49 AM   #1 (permalink)
xenon
The Frequenter
Newcomer 
 
xenon's Avatar
 
Join Date: Dec 2007
Location: Bucharest, Romania
Posts: 438
Thanks: 3
xenon is on a distinguished road
Default Registry pattern

Heard about it? Used it? I've already implemented it and it's a life saver. I bet there are many more interesting patterns to follow, but I really needed this one, so I could stop passing an object over and over again through the constructors and such and I didn't even know it exists :P

My implementation:

PHP Code:
final class Registry
{
    
/**
     * 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$nameself::$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();
        }
    }

And by the way, "Design patterns" from Wordware is well worth reading. An excelent object oriented reference book.
__________________
I have optimistic thoughts, even though sometimes (if not always) life's a bitch.

Last edited by xenon : 05-05-2008 at 10:11 PM.
xenon is offline  
Reply With Quote
The Following 3 Users Say Thank You to xenon For This Useful Post:
drewbee (05-06-2008), jaegerschnitzel (02-15-2008), vpopp (12-04-2009)