views:

44

answers:

2

I have a webapplication where I use a registry class. The registry class holds important classes that I need troughout my application.

I have made the registry class a Singleton class and this class is static.

The content of the registry class is here:

<?php
class registry
{
    private static $objects = array();
    private static $instance;

    private function __construct(){}
    private function __clone(){}

    public static function singleton()
    {
        if( !isset( self::$instance ) )
        {
            self::$instance = new registry();
        }
        return self::$instance;
    }

    public function storeObjects()
    {
        $Objects = array_merge($GLOBALS['EXTRA_LIBS'],array('data','page','session','uri','loader','modules'));

        foreach($Objects as $name)
        {
            $this->$name  = $name;
        }
    }

    public function __set( $object, $key )
    {
        require_once(__LIBRARIES . DS . $object . '.class.php');
        self::$objects[ $key ] = new $object( self::$instance );
    }

    public function __get( $key )
    {
        if( is_object ( self::$objects[ $key ] ) )
        {
            return self::$objects[ $key ];
        }
    }

    public function returnAllObjects()
    {
        return self::$objects;
    }
}
?>

Now whenever I want to use one of the classes here in my application I do:

registry::singleton()->data->adddata('somedata');

I use the classes a lot in my application, minimum of 1 time in every method.

Now my question is what is the best thing to do:

1) call the whole thing everytime

2) Class $registry = registry::singleton(); one time in every method and then just use the local variable. (I do not know if this will work)

Or is there a more elegant method to tackle this problem.

A: 

(2) would work just fine, try it. If you're using it a few times in each method it will save you some typing.

You could consider adding some sanity checking in __set() to make sure the file exists before require_once, as well as logging and/or returning an error if it doesn't (same for __get()).

Fanis
+1  A: 

Whether you assign the registry instance to a local variable or not is irrelevant. If this is your only concern, use what makes the code more readable in the specific block of code.

I'd be more concerned about the implications of having to hardcode the Registry classname into my other classes and whether I really need a Singleton for the Registry. Have a look at Dependency Injection.

Gordon
+1 for dependency injection
Michael Aaron Safyan