Guest User

Untitled

a guest
Jan 29th, 2013
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.05 KB | None | 0 0
  1. <?php
  2.  
  3. class Registry {
  4.  
  5.     private function __construct() {}
  6.     private function __clone() {}
  7.  
  8.     public static function clear() {
  9.         $self = self::getInstance();
  10.         $self->storage = array();
  11.         return $self;
  12.     }
  13.  
  14.     public static function add($name, $instance) {
  15.         $self = self::getInstance();
  16.         $self->ensureIsFree($name);
  17.         if (!is_object($instance)) {
  18.             throw new \ InvalidArgumentException('Instance is not an object');
  19.         }
  20.         $self->storage[$name] = $instance;
  21.         return $self;
  22.     }
  23.  
  24.     public static function addLazy($name, $class_name, array $constructor_arguments = array()) {
  25.         $self = self::getInstance();
  26.         $self->ensureIsFree($name);
  27.         $self->storage[$name] = array((string)$class_name, $constructor_arguments);
  28.         return $self;
  29.     }
  30.  
  31.     public static function __callStatic($name, $arguments_ignored) {
  32.         $self = self::getInstance();
  33.         if (!isset($self->storage[$name])) {
  34.             throw new \ LogicException("No instance for name '$name' is registered");
  35.         }
  36.         $instance = $self->storage[$name];
  37.         if (is_array($instance)) {
  38.             list($class_name, $constructor_arguments) = $instance;
  39.             $instance = call_user_func_array(
  40.                 array(new \ ReflectionClass($class_name), 'newInstance'),
  41.                 $constructor_arguments
  42.             );
  43.             $self->storage[$name] = $instance;
  44.         }
  45.         return $instance;
  46.     }
  47.  
  48.     protected function ensureIsFree($name) {
  49.         if (isset($this->storage[$name])) {
  50.             throw new \ LogicException("An instance named '$name' is already registered");
  51.         }
  52.     }
  53.  
  54.     protected function getInstance() {
  55.         if (null === self::$instance) {
  56.             self::$instance = new self;
  57.         }
  58.         return self::$instance;
  59.     }
  60.  
  61.     public static function setInstance($instance) {
  62.         self::$instance = $instance;
  63.     }
  64.  
  65.     private $storage = array();
  66.     private static $instance = null;
  67.  
  68. }
Advertisement
Add Comment
Please, Sign In to add comment