Container
API reference › yii › di › Container
Container implements a 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.
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. The 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:
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.
Properties
Section titled “Properties”| Property | Type | Description | Defined by |
|---|---|---|---|
$behaviors read-only | array<yii\<static>> | List of behaviors attached to this component. | yii\ |
$definitions | array | The list of the object definitions or the loaded shared objects (type or ID => definition or instance). | Container |
$resolveArrays write-only | bool | Whether to attempt to resolve elements in array dependencies. | Container |
$singleton write-only | string | Class name, interface name or alias name | Container |
$singletons write-only | array | Array of singleton definitions. | Container |
Methods
Section titled “Methods”| Method | Description | Defined by |
|---|---|---|
__construct() | Constructor. | yii\ |
__call() | Calls the named method which is not a class method. | yii\ |
__clone() | This method is called after the object is created by cloning an existing one. | yii\ |
__get() | Returns the value of a component property. | yii\ |
__isset() | Checks if a property is set, i.e. defined and not null. | yii\ |
__set() | Sets the value of a component property. | yii\ |
__unset() | Sets a component property to be null. | yii\ |
attachBehavior() | Attaches a behavior to this component. | yii\ |
attachBehaviors() | Attaches a list of behaviors to the component. | yii\ |
behaviors() | Returns a list of behaviors that this component should behave as. | yii\ |
canGetProperty() | Returns a value indicating whether a property can be read. | yii\ |
canSetProperty() | Returns a value indicating whether a property can be set. | yii\ |
className() static | Returns the fully qualified name of this class. | yii\ |
clear() | Removes the definition for the specified name. | Container |
detachBehavior() | Detaches a behavior from the component. | yii\ |
detachBehaviors() | Detaches all behaviors from the component. | yii\ |
ensureBehaviors() | Makes sure that the behaviors declared in behaviors() are attached to this component. | yii\ |
get() | Returns an instance of the requested class. | Container |
getBehavior() | Returns the named behavior object. | yii\ |
getBehaviors() | Returns all behaviors attached to this component. | yii\ |
getDefinitions() | Returns the list of the object definitions or the loaded shared objects. | Container |
has() | Returns a value indicating whether the container has the definition of the specified name. | Container |
hasEventHandlers() | Returns a value indicating whether there is any handler attached to the named event. | yii\ |
hasMethod() | Returns a value indicating whether a method is defined. | yii\ |
hasProperty() | Returns a value indicating whether a property is defined for this component. | yii\ |
hasSingleton() | Returns a value indicating whether the given name corresponds to a registered singleton. | Container |
init() | Initializes the object. | yii\ |
invoke() | Invoke a callback with resolving dependencies in parameters. | Container |
off() | Detaches an existing event handler from this component. | yii\ |
on() | Attaches an event handler to an event. | yii\ |
resolveCallableDependencies() | Resolve dependencies for a function. | Container |
set() | Registers a class definition with this container. | Container |
setDefinitions() | Registers class definitions within this container. | Container |
setResolveArrays() | Container | |
setSingleton() | Registers a class definition with this container and marks the class as a singleton class. | Container |
setSingletons() | Registers class definitions as singletons within this container by calling setSingleton(). | Container |
trigger() | Triggers an event. | yii\ |
build() protected | Creates an instance of the specified class. | Container |
getDependencies() protected | Returns the dependencies of the specified class. | Container |
mergeParams() protected | Merges the user-specified constructor parameters with the ones registered via set(). | Container |
normalizeDefinition() protected | Normalizes the class definition. | Container |
resolveDependencies() protected | Resolves dependencies by replacing them with the actual object instances. | Container |
Property details
Section titled “Property details”$singletons
Section titled “$singletons ”public array $singletonsArray of singleton definitions.
See setDefinitions() for allowed
formats of array.
Access
Write-only (virtual property).
Method details
Section titled “Method details”clear()
Section titled “clear() ”public function clear(string $class): mixedRemoves the definition for the specified name.
Parameters
| Parameter | Type | Description |
|---|---|---|
$class | string | Class name, interface name or alias name |
Returns
mixed
get()
Section titled “get() ”public function get(string|class-string<yii\di\T>|yii\di\Instance $class, array $params = [], array $config = []): ($class is class-string<yii\di\T> ? yii\di\T : object)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 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.
Parameters
| Parameter | Type | Description |
|---|---|---|
$class | string|Instance | The class Instance, name, or an alias name (e.g. foo) that was previously registered via set() or setSingleton(). |
$params | array | 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. |
$config | array | A list of name-value pairs that will be used to initialize the object properties. |
Returns
($class is class-string<yii\di\T> ? yii\di\T : object): An instance of the requested class.
Throws
yii\base\InvalidConfigException: if the class cannot be recognized or correspond to an invalid definitionNotInstantiableException: If resolved to an abstract class or an interface (since 2.0.9)
getDefinitions()
Section titled “getDefinitions() ”public function getDefinitions(): arrayReturns the list of the object definitions or the loaded shared objects.
Returns
array: The list of the object definitions or the loaded shared objects (type or ID => definition or instance).
has()
Section titled “has() ”public function has(string $class): boolReturns a value indicating whether the container has the definition of the specified name.
Parameters
| Parameter | Type | Description |
|---|---|---|
$class | string | Class name, interface name or alias name |
Returns
bool: Whether the container has the definition of the specified name.
See also
hasSingleton()
Section titled “hasSingleton() ”public function hasSingleton(string $class, bool $checkInstance = false): boolReturns a value indicating whether the given name corresponds to a registered singleton.
Parameters
| Parameter | Type | Description |
|---|---|---|
$class | string | Class name, interface name or alias name |
$checkInstance | bool | Whether to check if the singleton has been instantiated. |
Returns
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.
invoke()
Section titled “invoke() ”public function invoke(callable $callback, array $params = []): mixedInvoke a callback with resolving dependencies in parameters.
This method allows invoking a callback and let type hinted parameter names to be resolved as objects of the Container. It additionally allows calling function using named parameters.
For example, the following callback may be invoked using the Container to resolve the formatter dependency:
$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.
Parameters
| Parameter | Type | Description |
|---|---|---|
$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. |
Returns
mixed: The callback return value.
Throws
yii\base\InvalidConfigException: if a dependency cannot be resolved or if a dependency cannot be fulfilled.NotInstantiableException: If resolved to an abstract class or an interface (since 2.0.9)
Since
2.0.7
resolveCallableDependencies()
Section titled “resolveCallableDependencies() ”public function resolveCallableDependencies(callable $callback, array $params = []): arrayResolve dependencies for a function.
This method can be used to implement similar functionality as provided by invoke() in other
components.
Parameters
| Parameter | Type | Description |
|---|---|---|
$callback | callable | Callable to be invoked. |
$params | array | The array of parameters for the function, can be either numeric or associative. |
Returns
array: The resolved dependencies.
Throws
yii\base\InvalidConfigException: if a dependency cannot be resolved or if a dependency cannot be fulfilled.NotInstantiableException: If resolved to an abstract class or an interface (since 2.0.9)
Since
2.0.7
set()
Section titled “set() ”public function set(string $class, mixed $definition = [], array $params = []): $thisRegisters a class definition with this container.
For example,
// 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.
Parameters
| Parameter | Type | Description |
|---|---|---|
$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,, 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 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. |
Returns
$this: The container itself
setDefinitions()
Section titled “setDefinitions() ”public function setDefinitions(array $definitions): mixedRegisters class definitions within this container.
Parameters
| Parameter | Type | Description |
|---|---|---|
$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: $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: $container->setDefinitions([ ‘foo\Bar’ => [ [‘class’ => ‘app\Bar’], [Instance::of(‘baz’)] ] ]); |
Returns
mixed
Since
2.0.11
See also
set()(to know more about possible values of definitions)
setResolveArrays()
Section titled “setResolveArrays() ”public function setResolveArrays(bool $value): mixedParameters
| Parameter | Type | Description |
|---|---|---|
$value | bool | Whether to attempt to resolve elements in array dependencies |
Returns
mixed
Since
2.0.37
setSingleton()
Section titled “setSingleton() ”public function setSingleton(string $class, mixed $definition = [], array $params = []): $thisRegisters 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.
Parameters
| Parameter | Type | Description |
|---|---|---|
$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. |
Returns
$this: The container itself
See also
setSingletons()
Section titled “setSingletons() ”public function setSingletons(array $singletons): mixedRegisters class definitions as singletons within this container by calling setSingleton().
Parameters
| Parameter | Type | Description |
|---|---|---|
$singletons | array | Array of singleton definitions. See setDefinitions() for allowed formats of array. |
Returns
mixed
Since
2.0.11
See also
setDefinitions()(for allowed formats of $singletons parameter)setSingleton()(to know more about possible values of definitions)
build()
Section titled “build() ”protected function build(class-string<yii\di\T> $class, array $params, array $config): yii\di\TCreates 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.
Parameters
| Parameter | Type | Description |
|---|---|---|
$class | class-string<yii\ | The class name |
$params | array | Constructor parameters |
$config | array | Configurations to be applied to the new instance |
Returns
yii\di\T: The newly created instance of the specified class
Throws
NotInstantiableException: If resolved to an abstract class or an interface (since 2.0.9)
getDependencies()
Section titled “getDependencies() ”protected function getDependencies(class-string<yii\di\T> $class): array{ReflectionClass<yii\di\T>, array<string, mixed>}Returns the dependencies of the specified class.
Parameters
| Parameter | Type | Description |
|---|---|---|
$class | class-string<yii\ | Class name, interface name or alias name |
Returns
array{ReflectionClass<yii\di\T>, array<string, mixed>}: The dependencies of the specified class.
Throws
NotInstantiableException: if a dependency cannot be resolved or if a dependency cannot be fulfilled.
mergeParams()
Section titled “mergeParams() ”protected function mergeParams(string $class, array $params): arrayMerges the user-specified constructor parameters with the ones registered via set().
Parameters
| Parameter | Type | Description |
|---|---|---|
$class | string | Class name, interface name or alias name |
$params | array | The constructor parameters |
Returns
array: The merged parameters
normalizeDefinition()
Section titled “normalizeDefinition() ”protected function normalizeDefinition(string $class, string|array|callable $definition): arrayNormalizes the class definition.
Parameters
| Parameter | Type | Description |
|---|---|---|
$class | string | Class name |
$definition | string| | The class definition |
Returns
array: The normalized class definition
Throws
yii\base\InvalidConfigException: if the definition is invalid.
resolveDependencies()
Section titled “resolveDependencies() ”protected function resolveDependencies(array $dependencies, ReflectionClass<object>|null $reflection = null): arrayResolves dependencies by replacing them with the actual object instances.
Parameters
| Parameter | Type | Description |
|---|---|---|
$dependencies | array | The dependencies |
$reflection | ReflectionClass<object>| | The class reflection associated with the dependencies |
Returns
array: The resolved dependencies
Throws
yii\base\InvalidConfigException: if a dependency cannot be resolved or if a dependency cannot be fulfilled.