PHP Класс yii\di\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. Container supports constructor injection as well as property injection. To use Container, you first need to set up the class dependencies by calling Container::set. You then call Container::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); For more details and usage information on Container, see the guide article on di-containers.
С версии: 2.0
Автор: Qiang Xue ([email protected])
Наследование: extends yii\base\Component
Показать файл Открыть проект Примеры использования класса

Открытые методы

Метод Описание
clear ( string $class ) Removes the definition for the specified name.
get ( string $class, array $params = [], array $config = [] ) : object Returns an instance of the requested class.
getDefinitions ( ) : array Returns the list of the object definitions or the loaded shared objects.
has ( string $class ) : boolean Returns a value indicating whether the container has the definition of the specified name.
hasSingleton ( string $class, boolean $checkInstance = false ) : boolean Returns a value indicating whether the given name corresponds to a registered singleton.
invoke ( callable $callback, array $params = [] ) : mixed Invoke a callback with resolving dependencies in parameters.
resolveCallableDependencies ( callable $callback, array $params = [] ) : array Resolve dependencies for a function.
set ( string $class, mixed $definition = [], array $params = [] ) Registers a class definition with this container.
setDefinitions ( array $definitions ) Registers class definitions within this container.
setSingleton ( string $class, mixed $definition = [], array $params = [] ) Registers a class definition with this container and marks the class as a singleton class.
setSingletons ( array $singletons ) Registers class definitions as singletons within this container by calling Container::setSingleton

Защищенные методы

Метод Описание
build ( string $class, array $params, array $config ) : object Creates an instance of the specified class.
getDependencies ( string $class ) : array Returns the dependencies of the specified class.
mergeParams ( string $class, array $params ) : array Merges the user-specified constructor parameters with the ones registered via Container::set.
normalizeDefinition ( string $class, string | array | callable $definition ) : array Normalizes the class definition.
resolveDependencies ( array $dependencies, ReflectionClass $reflection = null ) : array Resolves dependencies by replacing them with the actual object instances.

Описание методов

build() защищенный Метод

This method will resolve dependencies of the specified class, instantiate them, and inject them into the new instance of the specified class.
protected build ( string $class, array $params, array $config ) : object
$class string the class name
$params array constructor parameters
$config array configurations to be applied to the new instance
Результат object the newly created instance of the specified class

clear() публичный Метод

Removes the definition for the specified name.
public clear ( string $class )
$class string class name, interface name or alias name

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 Container::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.
public get ( string $class, array $params = [], array $config = [] ) : object
$class string the class name or an alias name (e.g. `foo`) that was previously registered via [[set()]] or [[setSingleton()]].
$params array 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.
$config array a list of name-value pairs that will be used to initialize the object properties.
Результат object an instance of the requested class.

getDefinitions() публичный Метод

Returns the list of the object definitions or the loaded shared objects.
public getDefinitions ( ) : array
Результат array the list of the object definitions or the loaded shared objects (type or ID => definition or instance).

getDependencies() защищенный Метод

Returns the dependencies of the specified class.
protected getDependencies ( string $class ) : array
$class string class name, interface name or alias name
Результат array the dependencies of the specified class.

has() публичный Метод

Returns a value indicating whether the container has the definition of the specified name.
См. также: set()
public has ( string $class ) : boolean
$class string class name, interface name or alias name
Результат boolean whether the container has the definition of the specified name..

hasSingleton() публичный Метод

Returns a value indicating whether the given name corresponds to a registered singleton.
public hasSingleton ( string $class, boolean $checkInstance = false ) : boolean
$class string class name, interface name or alias name
$checkInstance boolean whether to check if the singleton has been instantiated.
Результат 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.

invoke() публичный Метод

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.
С версии: 2.0.7
public invoke ( callable $callback, array $params = [] ) : mixed
$callback callable callable to be invoked.
$params array The array of parameters for the function. This can be either a list of parameters, or an associative array representing named function parameters.
Результат mixed the callback return value.

mergeParams() защищенный Метод

Merges the user-specified constructor parameters with the ones registered via Container::set.
protected mergeParams ( string $class, array $params ) : array
$class string class name, interface name or alias name
$params array the constructor parameters
Результат array the merged parameters

normalizeDefinition() защищенный Метод

Normalizes the class definition.
protected normalizeDefinition ( string $class, string | array | callable $definition ) : array
$class string class name
$definition string | array | callable the class definition
Результат array the normalized class definition

resolveCallableDependencies() публичный Метод

This method can be used to implement similar functionality as provided by Container::invoke in other components.
С версии: 2.0.7
public resolveCallableDependencies ( callable $callback, array $params = [] ) : array
$callback callable callable to be invoked.
$params array The array of parameters for the function, can be either numeric or associative.
Результат array The resolved dependencies.

resolveDependencies() защищенный Метод

Resolves dependencies by replacing them with the actual object instances.
protected resolveDependencies ( array $dependencies, ReflectionClass $reflection = null ) : array
$dependencies array the dependencies
$reflection ReflectionClass the class reflection associated with the dependencies
Результат array the resolved dependencies

set() публичный Метод

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 Container::has to check if a class definition already exists.
public set ( string $class, mixed $definition = [], array $params = [] )
$class string class name, interface name or alias name
$definition mixed 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.
$params array the list of constructor parameters. The parameters will be passed to the class constructor when [[get()]] is called.

setDefinitions() публичный Метод

Registers class definitions within this container.
См. также: set() to know more about possible values of definitions
С версии: 2.0.11
public setDefinitions ( array $definitions )
$definitions array 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')] ] ]); ```

setSingleton() публичный Метод

This method is similar to Container::set except that classes registered via this method will only have one instance. Each time Container::get is called, the same instance of the specified class will be returned.
См. также: set()
public setSingleton ( string $class, mixed $definition = [], array $params = [] )
$class string class name, interface name or alias name
$definition mixed the definition associated with `$class`. See [[set()]] for more details.
$params array the list of constructor parameters. The parameters will be passed to the class constructor when [[get()]] is called.

setSingletons() публичный Метод

Registers class definitions as singletons within this container by calling Container::setSingleton
См. также: setDefinitions() for allowed formats of $singletons parameter
См. также: setSingleton() to know more about possible values of definitions
С версии: 2.0.11
public setSingletons ( array $singletons )
$singletons array array of singleton definitions. See [[setDefinitions()]] for allowed formats of array.