Container,用于动态地创建、注入依赖单元,映射依赖关系等功能,减少了许多代码量,降低代码耦合程度,提高项目的可维护性。
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\Object; * use yii\db\Connection; * use yii\di\Container; * * interface UserFinderInterface * { * function findUser(); * } * * class UserFinder extends Object implements UserFinderInterface * { * public $db; * * public function __construct(Connection $db, $config = []) * { * $this->db = $db; * parent::__construct($config); * } * * public function findUser() * { * } * } * * class UserLister extends Object * { * 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); * ``` * * @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 * @var array 用于保存单例Singleton对象,以对象类型为键(类名、接口名、别名) */ private $_singletons = []; /** * @var array object definitions indexed by their types * @var array 用于保存依赖的定义,以对象类型为键(类名、接口名、别名) */ private $_definitions = []; /** * @var array constructor parameters indexed by object types * @var array 用于保存构造函数的参数,以对象类型为键(类名、接口名、别名) */ private $_params = []; /** * @var array cached ReflectionClass objects indexed by class/interface names * @var array 用于缓存ReflectionClass对象,以类名或接口名为键 */ 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. * @var array 用于缓存依赖信息,以类名或接口名为键 */ 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 */ 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); } // 创建 $_definitions[$class] 数组的副本 $definition = $this->_definitions[$class]; // 依赖的定义是个 PHP callable,则调用它 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 = []) { // 规范化 $definition 并写入 $_definitions[$class] $this->_definitions[$class] = $this->normalizeDefinition($class, $definition); // 将构造函数参数写入 $_params[$class] $this->_params[$class] = $params; // 删除$_singletons[$class] 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 = []) { // 规范化 $definition 并写入 $_definitions[$class] $this->_definitions[$class] = $this->normalizeDefinition($class, $definition); // 将构造函数参数写入 $_params[$class] $this->_params[$class] = $params; // 将$_singleton[$class]置为null,表示还未实例化 $this->_singletons[$class] = null; return $this; } /** * Returns a value indicating whether the container has the definition of the specified name. * 判断_definitions中是否定义该依赖 * @param string $class class name, interface name or alias name * @return boolean 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. * 判断_singletons中是否定义该依赖,如果$checkInstance为真,怎判断该依赖是否实例化 * @param string $class class name, interface name or alias name * @param boolean $checkInstance whether to check if the singleton has been instantiated. * @return boolean 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) { // $definition 是空的转换成 ['class' => $class] 形式 if (empty($definition)) { return ['class' => $class]; } elseif (is_string($definition)) {// $definition 是字符串,转换成 ['class' => $definition] 形式 return ['class' => $definition]; } elseif (is_callable($definition, true) || is_object($definition)) {// $definition 是PHP callable 或对象,则直接将其作为依赖的定义 return $definition; } elseif (is_array($definition)) { // $definition 是数组则确保该数组定义了 class 元素 if (!isset($definition['class'])) {//class 元素未定义 if (strpos($class, '\\') !== false) {//判断传入的$class是否符合条件 $definition['class'] = $class;//符合则将传入的 $class 作为该元素的值 } else {//否则抛出异常 throw new InvalidConfigException("A class definition requires a \"class\" member."); } } return $definition;//返回该数组 } else {//否则抛出异常 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 */ protected function build($class, $params, $config) { /* @var $reflection ReflectionClass */ // 调用上面提到的getDependencies来获取并缓存依赖信息,留意这里 list 的用法 list ($reflection, $dependencies) = $this->getDependencies($class); // 用传入的 $params 的内容补充、覆盖到依赖信息中 foreach ($params as $index => $param) { $dependencies[$index] = $param; } // 解析依赖信息,如果有依赖单元需要提前实例化,会在这一步完成 $dependencies = $this->resolveDependencies($dependencies, $reflection); if (empty($config)) { // 实例化这个对象 return $reflection->newInstanceArgs($dependencies); } if (!empty($dependencies) && $reflection->implementsInterface('yii\base\Configurable')) {//$dependencies不为空且实现了Configurable接口 // set $config as the last parameter (existing one will be overwritten) // 按照 Configurable 接口的要求,构造函数的最后一个参数为 $config 数组 $dependencies[count($dependencies) - 1] = $config; // 实例化这个对象 return $reflection->newInstanceArgs($dependencies); } else { //否则实例化这个对象,将配置以属性的形式写入 $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()]]. * 合并 [[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]; } else { $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]]; } // 使用PHP5 的反射机制来获取类的有关信息,主要就是为了获取依赖信息 $dependencies = []; $reflection = new ReflectionClass($class); // 通过类的构建函数的参数来了解这个类依赖于哪些单元 $constructor = $reflection->getConstructor(); if ($constructor !== null) { foreach ($constructor->getParameters() as $param) { if ($param->isDefaultValueAvailable()) { // 构造函数如果有默认值,将默认值作为依赖 $dependencies[] = $param->getDefaultValue(); } else { // 构造函数没有默认值,则为其创建一个引用, 就是前面提到的 Instance 类型。 $c = $param->getClass(); $dependencies[] = Instance::of($c === null ? null : $c->getName()); } } } // 将 ReflectionClass 对象缓存起来 $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) { // 前面getDependencies() 函数往 $_dependencies[] 中写入的是一个 Instance 数组 if ($dependency instanceof Instance) { if ($dependency->id !== null) { // 向容器索要所依赖的实例,递归调用 yii\di\Container::get() $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. * @since 2.0.7 */ public function invoke(callable $callback, $params = []) { if (is_callable($callback)) {//函数合法可调用,则解析$params中的依赖参数,调用该函数 return call_user_func_array($callback, $this->resolveCallableDependencies($callback, $params)); } else {//否则直接以$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. * @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 ($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 (Yii::$app->has($name) && ($obj = Yii::$app->get($name)) instanceof $className) { $args[] = $obj; } else { $args[] = $this->get($className); } } 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; } }