/ yii2  

Yii2 源码阅读 06 - DI

yii\di
|--- Container.php
|--- Instance.php
|--- NotInstantiableException.php
|--- ServiceLocator.php

参见:依赖注入容器(Dependency Injection Container)

Instance

Instance 代表 依赖注入(DI)容器 或 服务定位器 中已命名对象的一个引用。

可以使用 get() 来获取 id 引用的实际对象。

Instance 主要用于两个地方:

  • 在配置依赖项注入容器时,使用 Instance 引用类名、接口名或别名。容器可以稍后将引用解析为实际对象。
  • 在使用服务定位器来获取依赖对象的类中。

  • public $id; the component ID, class name, interface name or alias name

  • public $optional; 如果应该返回 null 而不是抛出异常

ensure

/**
* 将指定的 引用 解析为 实际对象,并确保它属于指定的类型。
*
* 引用可以指定为字符串或实例对象。如果是前者,它将被视为组件ID、类/接口名称或别名,这取决于容器类型。
*
* 如果不指定 container,该方法将首先尝试 `Yii::$app`,然后是 `Yii::$container`。
*
* @param object|string|array|static $reference 一个对象或对所需对象的引用。
* 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. 如果是 null 将不进行检查
* @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)) {
// $reference is array
$class = isset($reference['class']) ? $reference['class'] : $type;
if (!$container instanceof Container) {
// 如果 $container 不是 Container,则赋值 Yii::$container
$container = Yii::$container;
}
unset($reference['class']);
// 从容器中获取
$component = $container->get($class, [], $reference);
if ($type === null || $component instanceof $type) {
// $type is null 或者 $component 是 $type 的实例
// 检查 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 is string
$reference = new static($reference);
} elseif ($type === null || $reference instanceof $type) {
// $reference is object
return $reference;
}

if ($reference instanceof self) {
// $reference is Instance
try {
// 从 Instance 中获取,见下
$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) {
// to be checked
return $component;
}

throw new InvalidConfigException('"' . $reference->id . '" refers to a ' . get_class($component) . " component. $type is expected.");
}

// $type 不符合预期
$valueType = is_object($reference) ? get_class($reference) : gettype($reference);
throw new InvalidConfigException("Invalid data type: $valueType. $type is expected.");
}

例子:

use yii\db\Connection;

// returns Yii::$app->db
$db = Instance::ensure('db', Connection::class);
// returns an instance of Connection using the given configuration
$db = Instance::ensure(['dsn' => 'sqlite:path/to/my.db'], Connection::class);

get

/**
* 返回这个 Instance 对象引用的实际对象。
* @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)
{
try {
if ($container) {
return $container->get($this->id);
}
// 如果不指定 container,该方法将首先尝试 `Yii::$app`,然后是 `Yii::$container`
if (Yii::$app && Yii::$app->has($this->id)) {
return Yii::$app->get($this->id);
}

return Yii::$container->get($this->id);
} catch (Exception $e) {
if ($this->optional) {
return null;
}
throw $e;
}
}

var_export

/**
* 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']);
}

Container

Container implements a dependency injection container.

依赖注入(DI)容器是:一个知道如何实例化和配置对象的对象它们的所有依赖对象。

For more information about DI, please refer to Martin Fowler’s article.

要使用 Container,首先需要通过调用 set() 设置类依赖项。然后调用 get() 来创建一个新的类对象。

Container 将自动实例化依赖对象,将它们注入正在创建的对象,配置并最终返回新创建的对象。

默认情况下,[[\Yii::$container]]引用一个被[[\Yii::createObject()]使用的 container 实例。

property

  • @property-read array $definitions The list of the object definitions or the loaded shared objects (type or ID => definition or instance).
  • @property-write bool $resolveArrays Whether to attempt to resolve elements in array dependencies.
  • private $_singletons = []; singleton objects indexed by their types.
  • private $_definitions = []; equal $definitions.
  • private $$_params = []; constructor parameters indexed by object types.
  • private $_reflections = []; cached ReflectionClass objects indexed by class/interface names.
  • private $_dependencies = []; cached dependencies indexed by class/interface names. 每个类名都与构造函数参数类型或默认值的列表相关联。
  • private $_resolveArrays = false; whether to attempt to resolve elements in array dependencies.

set

/**
* Registers a class definition with this container.
*
* 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 相关的定义 `$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;
}

/**
* 规范化 the class definition.
* @param string $class class name
* @param string|array|callable $definition the class definition
* @return array the normalized class definition(返回值还有可能是 callable or object)
* @throws InvalidConfigException if the definition is invalid.
*/
protected function normalizeDefinition($class, $definition)
{
if (empty($definition)) {
// $definition 为空时
return ['class' => $class];
} elseif (is_string($definition)) {
// $definition definition is string
return ['class' => $definition];
} elseif ($definition instanceof Instance) {
// $definition is Instance
return ['class' => $definition->id];
} elseif (is_callable($definition, true) || is_object($definition)) {
// $definition is is_callable or is_object
return $definition;
} elseif (is_array($definition)) {
if (!isset($definition['class']) && isset($definition['__class'])) {
// 存在 __class,没有 class,class 设置为 __class
$definition['class'] = $definition['__class'];
unset($definition['__class']);
}
if (!isset($definition['class'])) {
// $definition 没有 class
if (strpos($class, '\\') !== false) {
// $class 包含 \
$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));
}

/**
* 用这个容器注册一个类定义,并将该类标记为单例类 a singleton class。
*
* 这个方法类似于 set(),只是通过这个方法注册的类只有一个实例。
* 每次调用 get() 时,都会返回指定类的同一个实例。
*
* @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;
}

举例:

// 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);
});

get

/**
* 返回被请求类的实例。
*
* 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|Instance $class the class Instance, 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. Use one of two definitions:
* - Parameters as name-value pairs, for example: `['posts' => PostRepository::class]`.
* - Parameters 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.
* Dependencies indexed by name and by position in the same array are not allowed.
* @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 ($class instanceof Instance) {
// Instance
$class = $class->id;
}
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;
}

build


/**
* 创建指定类的实例。
* 此方法将解析指定类的依赖项,实例化它们,并将它们注入指定类的新实例中。
* @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);

$addDependencies = [];
if (isset($config['__construct()'])) {
$addDependencies = $config['__construct()'];
unset($config['__construct()']);
}
foreach ($params as $index => $param) {
$addDependencies[$index] = $param;
}

$this->validateDependencies($addDependencies);

if ($addDependencies && is_int(key($addDependencies))) {
$dependencies = array_values($dependencies);
$dependencies = $this->mergeDependencies($dependencies, $addDependencies);
} else {
$dependencies = $this->mergeDependencies($dependencies, $addDependencies);
$dependencies = array_values($dependencies);
}

$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;
}



/**
* 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.
* @throws NotInstantiableException if a dependency cannot be resolved or if a dependency cannot be fulfilled.
*/
protected function getDependencies($class)
{
if (isset($this->_reflections[$class])) {
return [$this->_reflections[$class], $this->_dependencies[$class]];
}

$dependencies = [];
try {
$reflection = new ReflectionClass($class);
} catch (\ReflectionException $e) {
throw new NotInstantiableException(
$class,
'Failed to instantiate component or class "' . $class . '".',
0,
$e
);
}

$constructor = $reflection->getConstructor();
if ($constructor !== null) {
foreach ($constructor->getParameters() as $param) {
if (PHP_VERSION_ID >= 50600 && $param->isVariadic()) {
break;
}

if (PHP_VERSION_ID >= 80000) {
$c = $param->getType();
$isClass = false;
if ($c instanceof ReflectionNamedType) {
$isClass = !$c->isBuiltin();
}
} else {
try {
$c = $param->getClass();
} catch (ReflectionException $e) {
if (!$this->isNulledParam($param)) {
$notInstantiableClass = null;
if (PHP_VERSION_ID >= 70000) {
$type = $param->getType();
if ($type instanceof ReflectionNamedType) {
$notInstantiableClass = $type->getName();
}
}
throw new NotInstantiableException(
$notInstantiableClass,
$notInstantiableClass === null ? 'Can not instantiate unknown class.' : null
);
} else {
$c = null;
}
}
$isClass = $c !== null;
}
$className = $isClass ? $c->getName() : null;

if ($className !== null) {
$dependencies[$param->getName()] = Instance::of($className, $this->isNulledParam($param));
} else {
$dependencies[$param->getName()] = $param->isDefaultValueAvailable()
? $param->getDefaultValue()
: null;
}
}
}

$this->_reflections[$class] = $reflection;
$this->_dependencies[$class] = $dependencies;

return [$reflection, $dependencies];
}

exp

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);

Yii 在依赖住入(DI)容器之上实现了它的服务定位器。 当一个服务定位器尝试创建一个新的对象实例时,它会把调用转发到 DI 容器。 后者将会像前文所述那样自动解决依赖关系。

– EOF –