/** * Gets the Multiton instance referenced by key. * * Automatically creates an instance if non exists. If one instance already exists, the argument list is ignored. * * @param string $key The key of the Multiton instance to get. * @param mixed $args,... The arguments for creating the Multiton instance. * * @return Multiton The Multiton instance. */ public static function instance($key = 'default') { if (!is_string($key) and !empty($key)) { throw new \InvalidArgumentException("The \$key must be a non-empty string."); } $class = static::$T; if (!class_exists($class)) { throw new Exceptions\ClassNotFoundException("The class {$class} was not found."); } if (!array_key_exists($class, static::$instances) or !array_key_exists($key, static::$instances[$class])) { if (!array_key_exists($class, static::$cache)) { static::$cache[$class]['forgeable'] = Utils::class_implements($class, 'axelitus\\Patterns\\Interfaces\\Forgeable'); } $args = array_slice(func_get_args(), 1); if (static::$cache[$class]['forgeable']) { static::$instances[$class][$key] = call_user_func_array([$class, 'forge'], $args); } else { $ref = new \ReflectionClass($class); $ctor = $ref->getConstructor(); $ctor->setAccessible(true); static::$instances[$class][$key] = $ref->newInstanceWithoutConstructor(); $ctor->invokeArgs(static::$instances[$class][$key], $args); } } return static::$instances[$class][$key]; }
/** * Gets the current Singleton instance. * * Automatically creates an instance if non exists. If one instance already exists, the argument list is ignored. * * @param mixed $args,... The arguments for creating the Singleton instance. * * @return Singleton The Singleton instance. */ public static function instance() { $class = get_called_class(); if (!array_key_exists($class, static::$instances)) { if (!array_key_exists($class, static::$cache)) { static::$cache[$class]['forgeable'] = Utils::class_implements($class, 'axelitus\\Patterns\\Interfaces\\Forgeable'); } $args = func_get_args(); if (static::$cache[$class]['forgeable']) { static::$instances[$class] = call_user_func_array([$class, 'forge'], $args); } else { $ref = new \ReflectionClass($class); $ctor = $ref->getConstructor(); $ctor->setAccessible(true); static::$instances[$class] = $ref->newInstanceWithoutConstructor(); $ctor->invokeArgs(static::$instances[$class], $args); } } return static::$instances[$class]; }