Registry or Singleton pattern in PHP?

前端 未结 3 1753
慢半拍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: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)
    

提交回复
热议问题