init
This commit is contained in:
659
vendor/yiisoft/yii2/di/Container.php
vendored
Normal file
659
vendor/yiisoft/yii2/di/Container.php
vendored
Normal file
@@ -0,0 +1,659 @@
|
||||
<?php
|
||||
/**
|
||||
* @link http://www.yiiframework.com/
|
||||
* @copyright Copyright (c) 2008 Yii Software LLC
|
||||
* @license http://www.yiiframework.com/license/
|
||||
*/
|
||||
|
||||
namespace yii\di;
|
||||
|
||||
use ReflectionClass;
|
||||
use Yii;
|
||||
use yii\base\Component;
|
||||
use yii\base\InvalidConfigException;
|
||||
use yii\helpers\ArrayHelper;
|
||||
|
||||
/**
|
||||
* Container implements a [dependency injection](http://en.wikipedia.org/wiki/Dependency_injection) container.
|
||||
*
|
||||
* A dependency injection (DI) container is an object that knows how to instantiate and configure objects and
|
||||
* all their dependent objects. For more information about DI, please refer to
|
||||
* [Martin Fowler's article](http://martinfowler.com/articles/injection.html).
|
||||
*
|
||||
* Container supports constructor injection as well as property injection.
|
||||
*
|
||||
* To use Container, you first need to set up the class dependencies by calling [[set()]].
|
||||
* You then call [[get()]] to create a new class object. Container will automatically instantiate
|
||||
* dependent objects, inject them into the object being created, configure and finally return the newly created object.
|
||||
*
|
||||
* By default, [[\Yii::$container]] refers to a Container instance which is used by [[\Yii::createObject()]]
|
||||
* to create new object instances. You may use this method to replace the `new` operator
|
||||
* when creating a new object, which gives you the benefit of automatic dependency resolution and default
|
||||
* property configuration.
|
||||
*
|
||||
* Below is an example of using Container:
|
||||
*
|
||||
* ```php
|
||||
* namespace app\models;
|
||||
*
|
||||
* use yii\base\BaseObject;
|
||||
* use yii\db\Connection;
|
||||
* use yii\di\Container;
|
||||
*
|
||||
* interface UserFinderInterface
|
||||
* {
|
||||
* function findUser();
|
||||
* }
|
||||
*
|
||||
* class UserFinder extends BaseObject implements UserFinderInterface
|
||||
* {
|
||||
* public $db;
|
||||
*
|
||||
* public function __construct(Connection $db, $config = [])
|
||||
* {
|
||||
* $this->db = $db;
|
||||
* parent::__construct($config);
|
||||
* }
|
||||
*
|
||||
* public function findUser()
|
||||
* {
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* class UserLister extends BaseObject
|
||||
* {
|
||||
* public $finder;
|
||||
*
|
||||
* public function __construct(UserFinderInterface $finder, $config = [])
|
||||
* {
|
||||
* $this->finder = $finder;
|
||||
* parent::__construct($config);
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* $container = new Container;
|
||||
* $container->set('yii\db\Connection', [
|
||||
* 'dsn' => '...',
|
||||
* ]);
|
||||
* $container->set('app\models\UserFinderInterface', [
|
||||
* 'class' => 'app\models\UserFinder',
|
||||
* ]);
|
||||
* $container->set('userLister', 'app\models\UserLister');
|
||||
*
|
||||
* $lister = $container->get('userLister');
|
||||
*
|
||||
* // which is equivalent to:
|
||||
*
|
||||
* $db = new \yii\db\Connection(['dsn' => '...']);
|
||||
* $finder = new UserFinder($db);
|
||||
* $lister = new UserLister($finder);
|
||||
* ```
|
||||
*
|
||||
* For more details and usage information on Container, see the [guide article on di-containers](guide:concept-di-container).
|
||||
*
|
||||
* @property array $definitions The list of the object definitions or the loaded shared objects (type or ID =>
|
||||
* definition or instance). This property is read-only.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @since 2.0
|
||||
*/
|
||||
class Container extends Component
|
||||
{
|
||||
/**
|
||||
* @var array singleton objects indexed by their types
|
||||
*/
|
||||
private $_singletons = [];
|
||||
/**
|
||||
* @var array object definitions indexed by their types
|
||||
*/
|
||||
private $_definitions = [];
|
||||
/**
|
||||
* @var array constructor parameters indexed by object types
|
||||
*/
|
||||
private $_params = [];
|
||||
/**
|
||||
* @var array cached ReflectionClass objects indexed by class/interface names
|
||||
*/
|
||||
private $_reflections = [];
|
||||
/**
|
||||
* @var array cached dependencies indexed by class/interface names. Each class name
|
||||
* is associated with a list of constructor parameter types or default values.
|
||||
*/
|
||||
private $_dependencies = [];
|
||||
|
||||
|
||||
/**
|
||||
* Returns an instance of the requested class.
|
||||
*
|
||||
* You may provide constructor parameters (`$params`) and object configurations (`$config`)
|
||||
* that will be used during the creation of the instance.
|
||||
*
|
||||
* If the class implements [[\yii\base\Configurable]], the `$config` parameter will be passed as the last
|
||||
* parameter to the class constructor; Otherwise, the configuration will be applied *after* the object is
|
||||
* instantiated.
|
||||
*
|
||||
* Note that if the class is declared to be singleton by calling [[setSingleton()]],
|
||||
* the same instance of the class will be returned each time this method is called.
|
||||
* In this case, the constructor parameters and object configurations will be used
|
||||
* only if the class is instantiated the first time.
|
||||
*
|
||||
* @param string $class the class name or an alias name (e.g. `foo`) that was previously registered via [[set()]]
|
||||
* or [[setSingleton()]].
|
||||
* @param array $params a list of constructor parameter values. The parameters should be provided in the order
|
||||
* they appear in the constructor declaration. If you want to skip some parameters, you should index the remaining
|
||||
* ones with the integers that represent their positions in the constructor parameter list.
|
||||
* @param array $config a list of name-value pairs that will be used to initialize the object properties.
|
||||
* @return object an instance of the requested class.
|
||||
* @throws InvalidConfigException if the class cannot be recognized or correspond to an invalid definition
|
||||
* @throws NotInstantiableException If resolved to an abstract class or an interface (since 2.0.9)
|
||||
*/
|
||||
public function get($class, $params = [], $config = [])
|
||||
{
|
||||
if (isset($this->_singletons[$class])) {
|
||||
// singleton
|
||||
return $this->_singletons[$class];
|
||||
} elseif (!isset($this->_definitions[$class])) {
|
||||
return $this->build($class, $params, $config);
|
||||
}
|
||||
|
||||
$definition = $this->_definitions[$class];
|
||||
|
||||
if (is_callable($definition, true)) {
|
||||
$params = $this->resolveDependencies($this->mergeParams($class, $params));
|
||||
$object = call_user_func($definition, $this, $params, $config);
|
||||
} elseif (is_array($definition)) {
|
||||
$concrete = $definition['class'];
|
||||
unset($definition['class']);
|
||||
|
||||
$config = array_merge($definition, $config);
|
||||
$params = $this->mergeParams($class, $params);
|
||||
|
||||
if ($concrete === $class) {
|
||||
$object = $this->build($class, $params, $config);
|
||||
} else {
|
||||
$object = $this->get($concrete, $params, $config);
|
||||
}
|
||||
} elseif (is_object($definition)) {
|
||||
return $this->_singletons[$class] = $definition;
|
||||
} else {
|
||||
throw new InvalidConfigException('Unexpected object definition type: ' . gettype($definition));
|
||||
}
|
||||
|
||||
if (array_key_exists($class, $this->_singletons)) {
|
||||
// singleton
|
||||
$this->_singletons[$class] = $object;
|
||||
}
|
||||
|
||||
return $object;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a class definition with this container.
|
||||
*
|
||||
* For example,
|
||||
*
|
||||
* ```php
|
||||
* // register a class name as is. This can be skipped.
|
||||
* $container->set('yii\db\Connection');
|
||||
*
|
||||
* // register an interface
|
||||
* // When a class depends on the interface, the corresponding class
|
||||
* // will be instantiated as the dependent object
|
||||
* $container->set('yii\mail\MailInterface', 'yii\swiftmailer\Mailer');
|
||||
*
|
||||
* // register an alias name. You can use $container->get('foo')
|
||||
* // to create an instance of Connection
|
||||
* $container->set('foo', 'yii\db\Connection');
|
||||
*
|
||||
* // register a class with configuration. The configuration
|
||||
* // will be applied when the class is instantiated by get()
|
||||
* $container->set('yii\db\Connection', [
|
||||
* 'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
|
||||
* 'username' => 'root',
|
||||
* 'password' => '',
|
||||
* 'charset' => 'utf8',
|
||||
* ]);
|
||||
*
|
||||
* // register an alias name with class configuration
|
||||
* // In this case, a "class" element is required to specify the class
|
||||
* $container->set('db', [
|
||||
* 'class' => 'yii\db\Connection',
|
||||
* 'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
|
||||
* 'username' => 'root',
|
||||
* 'password' => '',
|
||||
* 'charset' => 'utf8',
|
||||
* ]);
|
||||
*
|
||||
* // register a PHP callable
|
||||
* // The callable will be executed when $container->get('db') is called
|
||||
* $container->set('db', function ($container, $params, $config) {
|
||||
* return new \yii\db\Connection($config);
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* If a class definition with the same name already exists, it will be overwritten with the new one.
|
||||
* You may use [[has()]] to check if a class definition already exists.
|
||||
*
|
||||
* @param string $class class name, interface name or alias name
|
||||
* @param mixed $definition the definition associated with `$class`. It can be one of the following:
|
||||
*
|
||||
* - a PHP callable: The callable will be executed when [[get()]] is invoked. The signature of the callable
|
||||
* should be `function ($container, $params, $config)`, where `$params` stands for the list of constructor
|
||||
* parameters, `$config` the object configuration, and `$container` the container object. The return value
|
||||
* of the callable will be returned by [[get()]] as the object instance requested.
|
||||
* - a configuration array: the array contains name-value pairs that will be used to initialize the property
|
||||
* values of the newly created object when [[get()]] is called. The `class` element stands for the
|
||||
* the class of the object to be created. If `class` is not specified, `$class` will be used as the class name.
|
||||
* - a string: a class name, an interface name or an alias name.
|
||||
* @param array $params the list of constructor parameters. The parameters will be passed to the class
|
||||
* constructor when [[get()]] is called.
|
||||
* @return $this the container itself
|
||||
*/
|
||||
public function set($class, $definition = [], array $params = [])
|
||||
{
|
||||
$this->_definitions[$class] = $this->normalizeDefinition($class, $definition);
|
||||
$this->_params[$class] = $params;
|
||||
unset($this->_singletons[$class]);
|
||||
return $this;
|
||||
}
|
||||
/**
|
||||
* Registers a class definition with this container and marks the class as a singleton class.
|
||||
*
|
||||
* This method is similar to [[set()]] except that classes registered via this method will only have one
|
||||
* instance. Each time [[get()]] is called, the same instance of the specified class will be returned.
|
||||
*
|
||||
* @param string $class class name, interface name or alias name
|
||||
* @param mixed $definition the definition associated with `$class`. See [[set()]] for more details.
|
||||
* @param array $params the list of constructor parameters. The parameters will be passed to the class
|
||||
* constructor when [[get()]] is called.
|
||||
* @return $this the container itself
|
||||
* @see set()
|
||||
*/
|
||||
public function setSingleton($class, $definition = [], array $params = [])
|
||||
{
|
||||
$this->_definitions[$class] = $this->normalizeDefinition($class, $definition);
|
||||
$this->_params[$class] = $params;
|
||||
$this->_singletons[$class] = null;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a value indicating whether the container has the definition of the specified name.
|
||||
* @param string $class class name, interface name or alias name
|
||||
* @return bool whether the container has the definition of the specified name..
|
||||
* @see set()
|
||||
*/
|
||||
public function has($class)
|
||||
{
|
||||
return isset($this->_definitions[$class]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a value indicating whether the given name corresponds to a registered singleton.
|
||||
* @param string $class class name, interface name or alias name
|
||||
* @param bool $checkInstance whether to check if the singleton has been instantiated.
|
||||
* @return bool whether the given name corresponds to a registered singleton. If `$checkInstance` is true,
|
||||
* the method should return a value indicating whether the singleton has been instantiated.
|
||||
*/
|
||||
public function hasSingleton($class, $checkInstance = false)
|
||||
{
|
||||
return $checkInstance ? isset($this->_singletons[$class]) : array_key_exists($class, $this->_singletons);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the definition for the specified name.
|
||||
* @param string $class class name, interface name or alias name
|
||||
*/
|
||||
public function clear($class)
|
||||
{
|
||||
unset($this->_definitions[$class], $this->_singletons[$class]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes the class definition.
|
||||
* @param string $class class name
|
||||
* @param string|array|callable $definition the class definition
|
||||
* @return array the normalized class definition
|
||||
* @throws InvalidConfigException if the definition is invalid.
|
||||
*/
|
||||
protected function normalizeDefinition($class, $definition)
|
||||
{
|
||||
if (empty($definition)) {
|
||||
return ['class' => $class];
|
||||
} elseif (is_string($definition)) {
|
||||
return ['class' => $definition];
|
||||
} elseif (is_callable($definition, true) || is_object($definition)) {
|
||||
return $definition;
|
||||
} elseif (is_array($definition)) {
|
||||
if (!isset($definition['class'])) {
|
||||
if (strpos($class, '\\') !== false) {
|
||||
$definition['class'] = $class;
|
||||
} else {
|
||||
throw new InvalidConfigException('A class definition requires a "class" member.');
|
||||
}
|
||||
}
|
||||
|
||||
return $definition;
|
||||
}
|
||||
|
||||
throw new InvalidConfigException("Unsupported definition type for \"$class\": " . gettype($definition));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the list of the object definitions or the loaded shared objects.
|
||||
* @return array the list of the object definitions or the loaded shared objects (type or ID => definition or instance).
|
||||
*/
|
||||
public function getDefinitions()
|
||||
{
|
||||
return $this->_definitions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an instance of the specified class.
|
||||
* This method will resolve dependencies of the specified class, instantiate them, and inject
|
||||
* them into the new instance of the specified class.
|
||||
* @param string $class the class name
|
||||
* @param array $params constructor parameters
|
||||
* @param array $config configurations to be applied to the new instance
|
||||
* @return object the newly created instance of the specified class
|
||||
* @throws NotInstantiableException If resolved to an abstract class or an interface (since 2.0.9)
|
||||
*/
|
||||
protected function build($class, $params, $config)
|
||||
{
|
||||
/* @var $reflection ReflectionClass */
|
||||
list($reflection, $dependencies) = $this->getDependencies($class);
|
||||
|
||||
foreach ($params as $index => $param) {
|
||||
$dependencies[$index] = $param;
|
||||
}
|
||||
|
||||
$dependencies = $this->resolveDependencies($dependencies, $reflection);
|
||||
if (!$reflection->isInstantiable()) {
|
||||
throw new NotInstantiableException($reflection->name);
|
||||
}
|
||||
if (empty($config)) {
|
||||
return $reflection->newInstanceArgs($dependencies);
|
||||
}
|
||||
|
||||
$config = $this->resolveDependencies($config);
|
||||
|
||||
if (!empty($dependencies) && $reflection->implementsInterface('yii\base\Configurable')) {
|
||||
// set $config as the last parameter (existing one will be overwritten)
|
||||
$dependencies[count($dependencies) - 1] = $config;
|
||||
return $reflection->newInstanceArgs($dependencies);
|
||||
}
|
||||
|
||||
$object = $reflection->newInstanceArgs($dependencies);
|
||||
foreach ($config as $name => $value) {
|
||||
$object->$name = $value;
|
||||
}
|
||||
|
||||
return $object;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges the user-specified constructor parameters with the ones registered via [[set()]].
|
||||
* @param string $class class name, interface name or alias name
|
||||
* @param array $params the constructor parameters
|
||||
* @return array the merged parameters
|
||||
*/
|
||||
protected function mergeParams($class, $params)
|
||||
{
|
||||
if (empty($this->_params[$class])) {
|
||||
return $params;
|
||||
} elseif (empty($params)) {
|
||||
return $this->_params[$class];
|
||||
}
|
||||
|
||||
$ps = $this->_params[$class];
|
||||
foreach ($params as $index => $value) {
|
||||
$ps[$index] = $value;
|
||||
}
|
||||
|
||||
return $ps;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the dependencies of the specified class.
|
||||
* @param string $class class name, interface name or alias name
|
||||
* @return array the dependencies of the specified class.
|
||||
*/
|
||||
protected function getDependencies($class)
|
||||
{
|
||||
if (isset($this->_reflections[$class])) {
|
||||
return [$this->_reflections[$class], $this->_dependencies[$class]];
|
||||
}
|
||||
|
||||
$dependencies = [];
|
||||
$reflection = new ReflectionClass($class);
|
||||
|
||||
$constructor = $reflection->getConstructor();
|
||||
if ($constructor !== null) {
|
||||
foreach ($constructor->getParameters() as $param) {
|
||||
if (version_compare(PHP_VERSION, '5.6.0', '>=') && $param->isVariadic()) {
|
||||
break;
|
||||
} elseif ($param->isDefaultValueAvailable()) {
|
||||
$dependencies[] = $param->getDefaultValue();
|
||||
} else {
|
||||
$c = $param->getClass();
|
||||
$dependencies[] = Instance::of($c === null ? null : $c->getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$this->_reflections[$class] = $reflection;
|
||||
$this->_dependencies[$class] = $dependencies;
|
||||
|
||||
return [$reflection, $dependencies];
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves dependencies by replacing them with the actual object instances.
|
||||
* @param array $dependencies the dependencies
|
||||
* @param ReflectionClass $reflection the class reflection associated with the dependencies
|
||||
* @return array the resolved dependencies
|
||||
* @throws InvalidConfigException if a dependency cannot be resolved or if a dependency cannot be fulfilled.
|
||||
*/
|
||||
protected function resolveDependencies($dependencies, $reflection = null)
|
||||
{
|
||||
foreach ($dependencies as $index => $dependency) {
|
||||
if ($dependency instanceof Instance) {
|
||||
if ($dependency->id !== null) {
|
||||
$dependencies[$index] = $this->get($dependency->id);
|
||||
} elseif ($reflection !== null) {
|
||||
$name = $reflection->getConstructor()->getParameters()[$index]->getName();
|
||||
$class = $reflection->getName();
|
||||
throw new InvalidConfigException("Missing required parameter \"$name\" when instantiating \"$class\".");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $dependencies;
|
||||
}
|
||||
|
||||
/**
|
||||
* Invoke a callback with resolving dependencies in parameters.
|
||||
*
|
||||
* This methods allows invoking a callback and let type hinted parameter names to be
|
||||
* resolved as objects of the Container. It additionally allow calling function using named parameters.
|
||||
*
|
||||
* For example, the following callback may be invoked using the Container to resolve the formatter dependency:
|
||||
*
|
||||
* ```php
|
||||
* $formatString = function($string, \yii\i18n\Formatter $formatter) {
|
||||
* // ...
|
||||
* }
|
||||
* Yii::$container->invoke($formatString, ['string' => 'Hello World!']);
|
||||
* ```
|
||||
*
|
||||
* This will pass the string `'Hello World!'` as the first param, and a formatter instance created
|
||||
* by the DI container as the second param to the callable.
|
||||
*
|
||||
* @param callable $callback callable to be invoked.
|
||||
* @param array $params The array of parameters for the function.
|
||||
* This can be either a list of parameters, or an associative array representing named function parameters.
|
||||
* @return mixed the callback return value.
|
||||
* @throws InvalidConfigException if a dependency cannot be resolved or if a dependency cannot be fulfilled.
|
||||
* @throws NotInstantiableException If resolved to an abstract class or an interface (since 2.0.9)
|
||||
* @since 2.0.7
|
||||
*/
|
||||
public function invoke(callable $callback, $params = [])
|
||||
{
|
||||
if (is_callable($callback)) {
|
||||
return call_user_func_array($callback, $this->resolveCallableDependencies($callback, $params));
|
||||
}
|
||||
|
||||
return call_user_func_array($callback, $params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve dependencies for a function.
|
||||
*
|
||||
* This method can be used to implement similar functionality as provided by [[invoke()]] in other
|
||||
* components.
|
||||
*
|
||||
* @param callable $callback callable to be invoked.
|
||||
* @param array $params The array of parameters for the function, can be either numeric or associative.
|
||||
* @return array The resolved dependencies.
|
||||
* @throws InvalidConfigException if a dependency cannot be resolved or if a dependency cannot be fulfilled.
|
||||
* @throws NotInstantiableException If resolved to an abstract class or an interface (since 2.0.9)
|
||||
* @since 2.0.7
|
||||
*/
|
||||
public function resolveCallableDependencies(callable $callback, $params = [])
|
||||
{
|
||||
if (is_array($callback)) {
|
||||
$reflection = new \ReflectionMethod($callback[0], $callback[1]);
|
||||
} else {
|
||||
$reflection = new \ReflectionFunction($callback);
|
||||
}
|
||||
|
||||
$args = [];
|
||||
|
||||
$associative = ArrayHelper::isAssociative($params);
|
||||
|
||||
foreach ($reflection->getParameters() as $param) {
|
||||
$name = $param->getName();
|
||||
if (($class = $param->getClass()) !== null) {
|
||||
$className = $class->getName();
|
||||
if (version_compare(PHP_VERSION, '5.6.0', '>=') && $param->isVariadic()) {
|
||||
$args = array_merge($args, array_values($params));
|
||||
break;
|
||||
} elseif ($associative && isset($params[$name]) && $params[$name] instanceof $className) {
|
||||
$args[] = $params[$name];
|
||||
unset($params[$name]);
|
||||
} elseif (!$associative && isset($params[0]) && $params[0] instanceof $className) {
|
||||
$args[] = array_shift($params);
|
||||
} elseif (isset(Yii::$app) && Yii::$app->has($name) && ($obj = Yii::$app->get($name)) instanceof $className) {
|
||||
$args[] = $obj;
|
||||
} else {
|
||||
// If the argument is optional we catch not instantiable exceptions
|
||||
try {
|
||||
$args[] = $this->get($className);
|
||||
} catch (NotInstantiableException $e) {
|
||||
if ($param->isDefaultValueAvailable()) {
|
||||
$args[] = $param->getDefaultValue();
|
||||
} else {
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
}
|
||||
} elseif ($associative && isset($params[$name])) {
|
||||
$args[] = $params[$name];
|
||||
unset($params[$name]);
|
||||
} elseif (!$associative && count($params)) {
|
||||
$args[] = array_shift($params);
|
||||
} elseif ($param->isDefaultValueAvailable()) {
|
||||
$args[] = $param->getDefaultValue();
|
||||
} elseif (!$param->isOptional()) {
|
||||
$funcName = $reflection->getName();
|
||||
throw new InvalidConfigException("Missing required parameter \"$name\" when calling \"$funcName\".");
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($params as $value) {
|
||||
$args[] = $value;
|
||||
}
|
||||
|
||||
return $args;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers class definitions within this container.
|
||||
*
|
||||
* @param array $definitions array of definitions. There are two allowed formats of array.
|
||||
* The first format:
|
||||
* - key: class name, interface name or alias name. The key will be passed to the [[set()]] method
|
||||
* as a first argument `$class`.
|
||||
* - value: the definition associated with `$class`. Possible values are described in
|
||||
* [[set()]] documentation for the `$definition` parameter. Will be passed to the [[set()]] method
|
||||
* as the second argument `$definition`.
|
||||
*
|
||||
* Example:
|
||||
* ```php
|
||||
* $container->setDefinitions([
|
||||
* 'yii\web\Request' => 'app\components\Request',
|
||||
* 'yii\web\Response' => [
|
||||
* 'class' => 'app\components\Response',
|
||||
* 'format' => 'json'
|
||||
* ],
|
||||
* 'foo\Bar' => function () {
|
||||
* $qux = new Qux;
|
||||
* $foo = new Foo($qux);
|
||||
* return new Bar($foo);
|
||||
* }
|
||||
* ]);
|
||||
* ```
|
||||
*
|
||||
* The second format:
|
||||
* - key: class name, interface name or alias name. The key will be passed to the [[set()]] method
|
||||
* as a first argument `$class`.
|
||||
* - value: array of two elements. The first element will be passed the [[set()]] method as the
|
||||
* second argument `$definition`, the second one — as `$params`.
|
||||
*
|
||||
* Example:
|
||||
* ```php
|
||||
* $container->setDefinitions([
|
||||
* 'foo\Bar' => [
|
||||
* ['class' => 'app\Bar'],
|
||||
* [Instance::of('baz')]
|
||||
* ]
|
||||
* ]);
|
||||
* ```
|
||||
*
|
||||
* @see set() to know more about possible values of definitions
|
||||
* @since 2.0.11
|
||||
*/
|
||||
public function setDefinitions(array $definitions)
|
||||
{
|
||||
foreach ($definitions as $class => $definition) {
|
||||
if (is_array($definition) && count($definition) === 2 && array_values($definition) === $definition) {
|
||||
$this->set($class, $definition[0], $definition[1]);
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->set($class, $definition);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers class definitions as singletons within this container by calling [[setSingleton()]].
|
||||
*
|
||||
* @param array $singletons array of singleton definitions. See [[setDefinitions()]]
|
||||
* for allowed formats of array.
|
||||
*
|
||||
* @see setDefinitions() for allowed formats of $singletons parameter
|
||||
* @see setSingleton() to know more about possible values of definitions
|
||||
* @since 2.0.11
|
||||
*/
|
||||
public function setSingletons(array $singletons)
|
||||
{
|
||||
foreach ($singletons as $class => $definition) {
|
||||
if (is_array($definition) && count($definition) === 2 && array_values($definition) === $definition) {
|
||||
$this->setSingleton($class, $definition[0], $definition[1]);
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->setSingleton($class, $definition);
|
||||
}
|
||||
}
|
||||
}
|
||||
187
vendor/yiisoft/yii2/di/Instance.php
vendored
Normal file
187
vendor/yiisoft/yii2/di/Instance.php
vendored
Normal file
@@ -0,0 +1,187 @@
|
||||
<?php
|
||||
/**
|
||||
* @link http://www.yiiframework.com/
|
||||
* @copyright Copyright (c) 2008 Yii Software LLC
|
||||
* @license http://www.yiiframework.com/license/
|
||||
*/
|
||||
|
||||
namespace yii\di;
|
||||
|
||||
use Yii;
|
||||
use yii\base\InvalidConfigException;
|
||||
|
||||
/**
|
||||
* Instance represents a reference to a named object in a dependency injection (DI) container or a service locator.
|
||||
*
|
||||
* You may use [[get()]] to obtain the actual object referenced by [[id]].
|
||||
*
|
||||
* Instance is mainly used in two places:
|
||||
*
|
||||
* - When configuring a dependency injection container, you use Instance to reference a class name, interface name
|
||||
* or alias name. The reference can later be resolved into the actual object by the container.
|
||||
* - In classes which use service locator to obtain dependent objects.
|
||||
*
|
||||
* The following example shows how to configure a DI container with Instance:
|
||||
*
|
||||
* ```php
|
||||
* $container = new \yii\di\Container;
|
||||
* $container->set('cache', [
|
||||
* 'class' => 'yii\caching\DbCache',
|
||||
* 'db' => Instance::of('db')
|
||||
* ]);
|
||||
* $container->set('db', [
|
||||
* 'class' => 'yii\db\Connection',
|
||||
* 'dsn' => 'sqlite:path/to/file.db',
|
||||
* ]);
|
||||
* ```
|
||||
*
|
||||
* And the following example shows how a class retrieves a component from a service locator:
|
||||
*
|
||||
* ```php
|
||||
* class DbCache extends Cache
|
||||
* {
|
||||
* public $db = 'db';
|
||||
*
|
||||
* public function init()
|
||||
* {
|
||||
* parent::init();
|
||||
* $this->db = Instance::ensure($this->db, 'yii\db\Connection');
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @since 2.0
|
||||
*/
|
||||
class Instance
|
||||
{
|
||||
/**
|
||||
* @var string the component ID, class name, interface name or alias name
|
||||
*/
|
||||
public $id;
|
||||
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
* @param string $id the component ID
|
||||
*/
|
||||
protected function __construct($id)
|
||||
{
|
||||
$this->id = $id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new Instance object.
|
||||
* @param string $id the component ID
|
||||
* @return Instance the new Instance object.
|
||||
*/
|
||||
public static function of($id)
|
||||
{
|
||||
return new static($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the specified reference into the actual object and makes sure it is of the specified type.
|
||||
*
|
||||
* The reference may be specified as a string or an Instance object. If the former,
|
||||
* it will be treated as a component ID, a class/interface name or an alias, depending on the container type.
|
||||
*
|
||||
* If you do not specify a container, the method will first try `Yii::$app` followed by `Yii::$container`.
|
||||
*
|
||||
* For example,
|
||||
*
|
||||
* ```php
|
||||
* use yii\db\Connection;
|
||||
*
|
||||
* // returns Yii::$app->db
|
||||
* $db = Instance::ensure('db', Connection::className());
|
||||
* // returns an instance of Connection using the given configuration
|
||||
* $db = Instance::ensure(['dsn' => 'sqlite:path/to/my.db'], Connection::className());
|
||||
* ```
|
||||
*
|
||||
* @param object|string|array|static $reference an object or a reference to the desired object.
|
||||
* You may specify a reference in terms of a component ID or an Instance object.
|
||||
* Starting from version 2.0.2, you may also pass in a configuration array for creating the object.
|
||||
* If the "class" value is not specified in the configuration array, it will use the value of `$type`.
|
||||
* @param string $type the class/interface name to be checked. If null, type check will not be performed.
|
||||
* @param ServiceLocator|Container $container the container. This will be passed to [[get()]].
|
||||
* @return object the object referenced by the Instance, or `$reference` itself if it is an object.
|
||||
* @throws InvalidConfigException if the reference is invalid
|
||||
*/
|
||||
public static function ensure($reference, $type = null, $container = null)
|
||||
{
|
||||
if (is_array($reference)) {
|
||||
$class = isset($reference['class']) ? $reference['class'] : $type;
|
||||
if (!$container instanceof Container) {
|
||||
$container = Yii::$container;
|
||||
}
|
||||
unset($reference['class']);
|
||||
$component = $container->get($class, [], $reference);
|
||||
if ($type === null || $component instanceof $type) {
|
||||
return $component;
|
||||
}
|
||||
|
||||
throw new InvalidConfigException('Invalid data type: ' . $class . '. ' . $type . ' is expected.');
|
||||
} elseif (empty($reference)) {
|
||||
throw new InvalidConfigException('The required component is not specified.');
|
||||
}
|
||||
|
||||
if (is_string($reference)) {
|
||||
$reference = new static($reference);
|
||||
} elseif ($type === null || $reference instanceof $type) {
|
||||
return $reference;
|
||||
}
|
||||
|
||||
if ($reference instanceof self) {
|
||||
try {
|
||||
$component = $reference->get($container);
|
||||
} catch (\ReflectionException $e) {
|
||||
throw new InvalidConfigException('Failed to instantiate component or class "' . $reference->id . '".', 0, $e);
|
||||
}
|
||||
if ($type === null || $component instanceof $type) {
|
||||
return $component;
|
||||
}
|
||||
|
||||
throw new InvalidConfigException('"' . $reference->id . '" refers to a ' . get_class($component) . " component. $type is expected.");
|
||||
}
|
||||
|
||||
$valueType = is_object($reference) ? get_class($reference) : gettype($reference);
|
||||
throw new InvalidConfigException("Invalid data type: $valueType. $type is expected.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the actual object referenced by this Instance object.
|
||||
* @param ServiceLocator|Container $container the container used to locate the referenced object.
|
||||
* If null, the method will first try `Yii::$app` then `Yii::$container`.
|
||||
* @return object the actual object referenced by this Instance object.
|
||||
*/
|
||||
public function get($container = null)
|
||||
{
|
||||
if ($container) {
|
||||
return $container->get($this->id);
|
||||
}
|
||||
if (Yii::$app && Yii::$app->has($this->id)) {
|
||||
return Yii::$app->get($this->id);
|
||||
}
|
||||
|
||||
return Yii::$container->get($this->id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Restores class state after using `var_export()`.
|
||||
*
|
||||
* @param array $state
|
||||
* @return Instance
|
||||
* @throws InvalidConfigException when $state property does not contain `id` parameter
|
||||
* @see var_export()
|
||||
* @since 2.0.12
|
||||
*/
|
||||
public static function __set_state($state)
|
||||
{
|
||||
if (!isset($state['id'])) {
|
||||
throw new InvalidConfigException('Failed to instantiate class "Instance". Required parameter "id" is missing');
|
||||
}
|
||||
|
||||
return new self($state['id']);
|
||||
}
|
||||
}
|
||||
39
vendor/yiisoft/yii2/di/NotInstantiableException.php
vendored
Normal file
39
vendor/yiisoft/yii2/di/NotInstantiableException.php
vendored
Normal file
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
/**
|
||||
* @link http://www.yiiframework.com/
|
||||
* @copyright Copyright (c) 2008 Yii Software LLC
|
||||
* @license http://www.yiiframework.com/license/
|
||||
*/
|
||||
|
||||
namespace yii\di;
|
||||
|
||||
use yii\base\InvalidConfigException;
|
||||
|
||||
/**
|
||||
* NotInstantiableException represents an exception caused by incorrect dependency injection container
|
||||
* configuration or usage.
|
||||
*
|
||||
* @author Sam Mousa <sam@mousa.nl>
|
||||
* @since 2.0.9
|
||||
*/
|
||||
class NotInstantiableException extends InvalidConfigException
|
||||
{
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function __construct($class, $message = null, $code = 0, \Exception $previous = null)
|
||||
{
|
||||
if ($message === null) {
|
||||
$message = "Can not instantiate $class.";
|
||||
}
|
||||
parent::__construct($message, $code, $previous);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string the user-friendly name of this exception
|
||||
*/
|
||||
public function getName()
|
||||
{
|
||||
return 'Not instantiable';
|
||||
}
|
||||
}
|
||||
264
vendor/yiisoft/yii2/di/ServiceLocator.php
vendored
Normal file
264
vendor/yiisoft/yii2/di/ServiceLocator.php
vendored
Normal file
@@ -0,0 +1,264 @@
|
||||
<?php
|
||||
/**
|
||||
* @link http://www.yiiframework.com/
|
||||
* @copyright Copyright (c) 2008 Yii Software LLC
|
||||
* @license http://www.yiiframework.com/license/
|
||||
*/
|
||||
|
||||
namespace yii\di;
|
||||
|
||||
use Closure;
|
||||
use Yii;
|
||||
use yii\base\Component;
|
||||
use yii\base\InvalidConfigException;
|
||||
|
||||
/**
|
||||
* ServiceLocator implements a [service locator](http://en.wikipedia.org/wiki/Service_locator_pattern).
|
||||
*
|
||||
* To use ServiceLocator, you first need to register component IDs with the corresponding component
|
||||
* definitions with the locator by calling [[set()]] or [[setComponents()]].
|
||||
* You can then call [[get()]] to retrieve a component with the specified ID. The locator will automatically
|
||||
* instantiate and configure the component according to the definition.
|
||||
*
|
||||
* For example,
|
||||
*
|
||||
* ```php
|
||||
* $locator = new \yii\di\ServiceLocator;
|
||||
* $locator->setComponents([
|
||||
* 'db' => [
|
||||
* 'class' => 'yii\db\Connection',
|
||||
* 'dsn' => 'sqlite:path/to/file.db',
|
||||
* ],
|
||||
* 'cache' => [
|
||||
* 'class' => 'yii\caching\DbCache',
|
||||
* 'db' => 'db',
|
||||
* ],
|
||||
* ]);
|
||||
*
|
||||
* $db = $locator->get('db'); // or $locator->db
|
||||
* $cache = $locator->get('cache'); // or $locator->cache
|
||||
* ```
|
||||
*
|
||||
* Because [[\yii\base\Module]] extends from ServiceLocator, modules and the application are all service locators.
|
||||
* Modules add [tree traversal](guide:concept-service-locator#tree-traversal) for service resolution.
|
||||
*
|
||||
* For more details and usage information on ServiceLocator, see the [guide article on service locators](guide:concept-service-locator).
|
||||
*
|
||||
* @property array $components The list of the component definitions or the loaded component instances (ID =>
|
||||
* definition or instance).
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
* @since 2.0
|
||||
*/
|
||||
class ServiceLocator extends Component
|
||||
{
|
||||
/**
|
||||
* @var array shared component instances indexed by their IDs
|
||||
*/
|
||||
private $_components = [];
|
||||
/**
|
||||
* @var array component definitions indexed by their IDs
|
||||
*/
|
||||
private $_definitions = [];
|
||||
|
||||
|
||||
/**
|
||||
* Getter magic method.
|
||||
* This method is overridden to support accessing components like reading properties.
|
||||
* @param string $name component or property name
|
||||
* @return mixed the named property value
|
||||
*/
|
||||
public function __get($name)
|
||||
{
|
||||
if ($this->has($name)) {
|
||||
return $this->get($name);
|
||||
}
|
||||
|
||||
return parent::__get($name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a property value is null.
|
||||
* This method overrides the parent implementation by checking if the named component is loaded.
|
||||
* @param string $name the property name or the event name
|
||||
* @return bool whether the property value is null
|
||||
*/
|
||||
public function __isset($name)
|
||||
{
|
||||
if ($this->has($name)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return parent::__isset($name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a value indicating whether the locator has the specified component definition or has instantiated the component.
|
||||
* This method may return different results depending on the value of `$checkInstance`.
|
||||
*
|
||||
* - If `$checkInstance` is false (default), the method will return a value indicating whether the locator has the specified
|
||||
* component definition.
|
||||
* - If `$checkInstance` is true, the method will return a value indicating whether the locator has
|
||||
* instantiated the specified component.
|
||||
*
|
||||
* @param string $id component ID (e.g. `db`).
|
||||
* @param bool $checkInstance whether the method should check if the component is shared and instantiated.
|
||||
* @return bool whether the locator has the specified component definition or has instantiated the component.
|
||||
* @see set()
|
||||
*/
|
||||
public function has($id, $checkInstance = false)
|
||||
{
|
||||
return $checkInstance ? isset($this->_components[$id]) : isset($this->_definitions[$id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the component instance with the specified ID.
|
||||
*
|
||||
* @param string $id component ID (e.g. `db`).
|
||||
* @param bool $throwException whether to throw an exception if `$id` is not registered with the locator before.
|
||||
* @return object|null the component of the specified ID. If `$throwException` is false and `$id`
|
||||
* is not registered before, null will be returned.
|
||||
* @throws InvalidConfigException if `$id` refers to a nonexistent component ID
|
||||
* @see has()
|
||||
* @see set()
|
||||
*/
|
||||
public function get($id, $throwException = true)
|
||||
{
|
||||
if (isset($this->_components[$id])) {
|
||||
return $this->_components[$id];
|
||||
}
|
||||
|
||||
if (isset($this->_definitions[$id])) {
|
||||
$definition = $this->_definitions[$id];
|
||||
if (is_object($definition) && !$definition instanceof Closure) {
|
||||
return $this->_components[$id] = $definition;
|
||||
}
|
||||
|
||||
return $this->_components[$id] = Yii::createObject($definition);
|
||||
} elseif ($throwException) {
|
||||
throw new InvalidConfigException("Unknown component ID: $id");
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a component definition with this locator.
|
||||
*
|
||||
* For example,
|
||||
*
|
||||
* ```php
|
||||
* // a class name
|
||||
* $locator->set('cache', 'yii\caching\FileCache');
|
||||
*
|
||||
* // a configuration array
|
||||
* $locator->set('db', [
|
||||
* 'class' => 'yii\db\Connection',
|
||||
* 'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
|
||||
* 'username' => 'root',
|
||||
* 'password' => '',
|
||||
* 'charset' => 'utf8',
|
||||
* ]);
|
||||
*
|
||||
* // an anonymous function
|
||||
* $locator->set('cache', function ($params) {
|
||||
* return new \yii\caching\FileCache;
|
||||
* });
|
||||
*
|
||||
* // an instance
|
||||
* $locator->set('cache', new \yii\caching\FileCache);
|
||||
* ```
|
||||
*
|
||||
* If a component definition with the same ID already exists, it will be overwritten.
|
||||
*
|
||||
* @param string $id component ID (e.g. `db`).
|
||||
* @param mixed $definition the component definition to be registered with this locator.
|
||||
* It can be one of the following:
|
||||
*
|
||||
* - a class name
|
||||
* - a configuration array: the array contains name-value pairs that will be used to
|
||||
* initialize the property values of the newly created object when [[get()]] is called.
|
||||
* The `class` element is required and stands for the the class of the object to be created.
|
||||
* - a PHP callable: either an anonymous function or an array representing a class method (e.g. `['Foo', 'bar']`).
|
||||
* The callable will be called by [[get()]] to return an object associated with the specified component ID.
|
||||
* - an object: When [[get()]] is called, this object will be returned.
|
||||
*
|
||||
* @throws InvalidConfigException if the definition is an invalid configuration array
|
||||
*/
|
||||
public function set($id, $definition)
|
||||
{
|
||||
unset($this->_components[$id]);
|
||||
|
||||
if ($definition === null) {
|
||||
unset($this->_definitions[$id]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (is_object($definition) || is_callable($definition, true)) {
|
||||
// an object, a class name, or a PHP callable
|
||||
$this->_definitions[$id] = $definition;
|
||||
} elseif (is_array($definition)) {
|
||||
// a configuration array
|
||||
if (isset($definition['class'])) {
|
||||
$this->_definitions[$id] = $definition;
|
||||
} else {
|
||||
throw new InvalidConfigException("The configuration for the \"$id\" component must contain a \"class\" element.");
|
||||
}
|
||||
} else {
|
||||
throw new InvalidConfigException("Unexpected configuration type for the \"$id\" component: " . gettype($definition));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the component from the locator.
|
||||
* @param string $id the component ID
|
||||
*/
|
||||
public function clear($id)
|
||||
{
|
||||
unset($this->_definitions[$id], $this->_components[$id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the list of the component definitions or the loaded component instances.
|
||||
* @param bool $returnDefinitions whether to return component definitions instead of the loaded component instances.
|
||||
* @return array the list of the component definitions or the loaded component instances (ID => definition or instance).
|
||||
*/
|
||||
public function getComponents($returnDefinitions = true)
|
||||
{
|
||||
return $returnDefinitions ? $this->_definitions : $this->_components;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a set of component definitions in this locator.
|
||||
*
|
||||
* This is the bulk version of [[set()]]. The parameter should be an array
|
||||
* whose keys are component IDs and values the corresponding component definitions.
|
||||
*
|
||||
* For more details on how to specify component IDs and definitions, please refer to [[set()]].
|
||||
*
|
||||
* If a component definition with the same ID already exists, it will be overwritten.
|
||||
*
|
||||
* The following is an example for registering two component definitions:
|
||||
*
|
||||
* ```php
|
||||
* [
|
||||
* 'db' => [
|
||||
* 'class' => 'yii\db\Connection',
|
||||
* 'dsn' => 'sqlite:path/to/file.db',
|
||||
* ],
|
||||
* 'cache' => [
|
||||
* 'class' => 'yii\caching\DbCache',
|
||||
* 'db' => 'db',
|
||||
* ],
|
||||
* ]
|
||||
* ```
|
||||
*
|
||||
* @param array $components component definitions or instances
|
||||
*/
|
||||
public function setComponents($components)
|
||||
{
|
||||
foreach ($components as $id => $component) {
|
||||
$this->set($id, $component);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user