PHP Class 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.
Since: 2.0
Author: Qiang Xue ([email protected])
Inheritance: extends yii\base\Component
Datei anzeigen Open project: yiisoft/yii2 Class Usage Examples

Public Methods

Method Description
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

Protected Methods

Method Description
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.

Method Details

build() protected method

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
return object the newly created instance of the specified class

clear() public method

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

get() public method

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.
return object an instance of the requested class.

getDefinitions() public method

Returns the list of the object definitions or the loaded shared objects.
public getDefinitions ( ) : array
return array the list of the object definitions or the loaded shared objects (type or ID => definition or instance).

getDependencies() protected method

Returns the dependencies of the specified class.
protected getDependencies ( string $class ) : array
$class string class name, interface name or alias name
return array the dependencies of the specified class.

has() public method

Returns a value indicating whether the container has the definition of the specified name.
See also: set()
public has ( string $class ) : boolean
$class string class name, interface name or alias name
return boolean whether the container has the definition of the specified name..

hasSingleton() public method

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.
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.

invoke() public method

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.
Since: 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.
return mixed the callback return value.

mergeParams() protected method

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
return array the merged parameters

normalizeDefinition() protected method

Normalizes the class definition.
protected normalizeDefinition ( string $class, string | array | callable $definition ) : array
$class string class name
$definition string | array | callable the class definition
return array the normalized class definition

resolveCallableDependencies() public method

This method can be used to implement similar functionality as provided by Container::invoke in other components.
Since: 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.
return array The resolved dependencies.

resolveDependencies() protected method

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
return array the resolved dependencies

set() public method

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() public method

Registers class definitions within this container.
See also: set() to know more about possible values of definitions
Since: 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() public method

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.
See also: 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() public method

Registers class definitions as singletons within this container by calling Container::setSingleton
See also: setDefinitions() for allowed formats of $singletons parameter
See also: setSingleton() to know more about possible values of definitions
Since: 2.0.11
public setSingletons ( array $singletons )
$singletons array array of singleton definitions. See [[setDefinitions()]] for allowed formats of array.