Registry or Singleton pattern in PHP?

前端 未结 3 1726
慢半拍i
慢半拍i 2021-01-11 19:52

I am working with PHP classes and objects now. In this question the names of fields and methods are made up just so you get an idea of what I am talking about.

It

相关标签:
3条回答
  • 2021-01-11 20:18

    You can implement lazy loading to only load the objects you really need:

    class Registry
    {
        private static $database = null;
    
        private static function connectDatabase($key)
        {
            [... do connection stuff ...]
        }
    
        public static function getDatabase($key)
        {
            if (Registry::$database == null)
            {
                Registry::connectDatabase($key);
            }
            return Registry::$database;
        }
    }
    

    The code to register the database connection parameters is left as exercise to the reader.

    0 讨论(0)
  • 2021-01-11 20:19

    That depends on your application. If you still need 3 out of the 4 classes, then it'd be more ideal to use the Registry than to handle the 3 independently only because you don't need the fourth. Loading the classes lazily would be one approach to reduce memory footprint, but then you need to instruct the registry when to create the objects and that's not much different than handling singletons. Alternatively, you could create an n-parameter constructor or use an array to instruct your Registry which classes to instantiate during construction.

    class Registry {
        public $class1;
        public $class2;
    
        function __construct($uses) {
            foreach($uses as $class) {
                $this->{$class} = new {$class}();
            }
        }
    
    }
    

    Then instantiate your Registry by specifying which classes to instantiate.

    $reg = new Registry(array('class1'));
    

    You would obviously want your constructor to handle zero parameters to account for instantiating all classes by default.

    0 讨论(0)
  • 2021-01-11 20:25

    Perhaps this is the proper Singleton-Registry pattern. OFC, you can implement different things, SplFixedArray, ArrayAccess interface, and others. Also it is not bad to add the destruct and destroy inner objects to ensure no leak possible.

    class oRegistry{
       private static $instance = null;
    
       private $storage = array();
    
       private function __construct(){}
    
       private function __clone(){}
    
       public static function getInstance(){
          if( self::$instance === null ){
             self::$instance = new self();
          }
          return self::$instance;
       }
    
       public function attach($name, $o) {
          if( true === isset($this->storage[$name]) ) {
              throw new Exception('The instance with name '.$name.' already exists in registry.');
          }
          if( !empty( $name ) ) {
              $this->storage[ $name ] = $o;
          }
       }
    
       public function detach( $name ){
           if( isset( $this->storage[ $name ] ) ) {
               $this->storage[ $name ] = null;
               unset( $this->storage[ $name ] );
           }
       }
    
       public function get( $name ){
           if( false === isset( $this->storage[$name] ) ) {
               throw new Exception('Invalid instance requested');
           }
           return $this->storage[ $name ];
       }
    }
    
    // usage example
    $storage = oRegistry::getInstance();
    $obj = new stdClass;
    $obj2 = new stdClass;
    $obj->test1 = 'test';
    $obj2->test2 = 't2';
    
    $storage->attach( 'test1', $obj );
    $storage->attach( 'test2', $obj2 );
    
    $got = $storage->get( 'test2' );
    var_dump($got); // object(stdClass)#3 (1) { ["test2"]=> string(2) "t2" }
    
    $storage->detach( 'test2' );
    $got = $storage->get( 'test2' );
    var_dump($got); // bool(false)
    
    0 讨论(0)
提交回复
热议问题