Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class Registry {
- private function __construct() {}
- private function __clone() {}
- public static function clear() {
- $self = self::getInstance();
- $self->storage = array();
- return $self;
- }
- public static function add($name, $instance) {
- $self = self::getInstance();
- $self->ensureIsFree($name);
- if (!is_object($instance)) {
- throw new \ InvalidArgumentException('Instance is not an object');
- }
- $self->storage[$name] = $instance;
- return $self;
- }
- public static function addLazy($name, $class_name, array $constructor_arguments = array()) {
- $self = self::getInstance();
- $self->ensureIsFree($name);
- $self->storage[$name] = array((string)$class_name, $constructor_arguments);
- return $self;
- }
- public static function __callStatic($name, $arguments_ignored) {
- $self = self::getInstance();
- if (!isset($self->storage[$name])) {
- throw new \ LogicException("No instance for name '$name' is registered");
- }
- $instance = $self->storage[$name];
- if (is_array($instance)) {
- list($class_name, $constructor_arguments) = $instance;
- $instance = call_user_func_array(
- array(new \ ReflectionClass($class_name), 'newInstance'),
- $constructor_arguments
- );
- $self->storage[$name] = $instance;
- }
- return $instance;
- }
- protected function ensureIsFree($name) {
- if (isset($this->storage[$name])) {
- throw new \ LogicException("An instance named '$name' is already registered");
- }
- }
- protected function getInstance() {
- if (null === self::$instance) {
- self::$instance = new self;
- }
- return self::$instance;
- }
- public static function setInstance($instance) {
- self::$instance = $instance;
- }
- private $storage = array();
- private static $instance = null;
- }
Advertisement
Add Comment
Please, Sign In to add comment