Creating a good registry class in PHP for important classes

I have a web application where I use a registry class. The registry class contains important classes that I need throughout my application.

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

The contents 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 that I want to use one of the classes here in my application, I:

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

I use classes a lot in my application, at least 1 time in each method.

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

1) call it all every time

2) A class $registry = registry::singleton();once in each method, and then just use a local variable. (I don't know if this will work)

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

+3
2

, . , , .

. .

+3

(2) , . , .

__set(), , require_once, / , ( __get()).

0

Source: https://habr.com/ru/post/1764444/


All Articles