Class yii\di\Container

Inheritanceyii\di\Container » yii\base\Component » yii\base\BaseObject
Implementsyii\base\Configurable
Available since version2.0
Source Code https://github.com/yiisoft/yii2/blob/master/framework/di/Container.php

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

Public Methods

Hide inherited methods

MethodDescriptionDefined By
__call() Calls the named method which is not a class method. yii\base\Component
__clone() This method is called after the object is created by cloning an existing one. yii\base\Component
__construct() Constructor. yii\base\BaseObject
__get() Returns the value of a component property. yii\base\Component
__isset() Checks if a property is set, i.e. defined and not null. yii\base\Component
__set() Sets the value of a component property. yii\base\Component
__unset() Sets a component property to be null. yii\base\Component
attachBehavior() Attaches a behavior to this component. yii\base\Component
attachBehaviors() Attaches a list of behaviors to the component. yii\base\Component
behaviors() Returns a list of behaviors that this component should behave as. yii\base\Component
canGetProperty() Returns a value indicating whether a property can be read. yii\base\Component
canSetProperty() Returns a value indicating whether a property can be set. yii\base\Component
className() Returns the fully qualified name of this class. yii\base\BaseObject
clear() Removes the definition for the specified name. yii\di\Container
detachBehavior() Detaches a behavior from the component. yii\base\Component
detachBehaviors() Detaches all behaviors from the component. yii\base\Component
ensureBehaviors() Makes sure that the behaviors declared in behaviors() are attached to this component. yii\base\Component
get() Returns an instance of the requested class. yii\di\Container
getBehavior() Returns the named behavior object. yii\base\Component
getBehaviors() Returns all behaviors attached to this component. yii\base\Component
getDefinitions() Returns the list of the object definitions or the loaded shared objects. yii\di\Container
has() Returns a value indicating whether the container has the definition of the specified name. yii\di\Container
hasEventHandlers() Returns a value indicating whether there is any handler attached to the named event. yii\base\Component
hasMethod() Returns a value indicating whether a method is defined. yii\base\Component
hasProperty() Returns a value indicating whether a property is defined for this component. yii\base\Component
hasSingleton() Returns a value indicating whether the given name corresponds to a registered singleton. yii\di\Container
init() Initializes the object. yii\base\BaseObject
invoke() Invoke a callback with resolving dependencies in parameters. yii\di\Container
off() Detaches an existing event handler from this component. yii\base\Component
on() Attaches an event handler to an event. yii\base\Component
resolveCallableDependencies() Resolve dependencies for a function. yii\di\Container
set() Registers a class definition with this container. yii\di\Container
setDefinitions() Registers class definitions within this container. yii\di\Container
setSingleton() Registers a class definition with this container and marks the class as a singleton class. yii\di\Container
setSingletons() Registers class definitions as singletons within this container by calling setSingleton(). yii\di\Container
trigger() Triggers an event. yii\base\Component

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
build() Creates an instance of the specified class. yii\di\Container
getDependencies() Returns the dependencies of the specified class. yii\di\Container
mergeParams() Merges the user-specified constructor parameters with the ones registered via set(). yii\di\Container
normalizeDefinition() Normalizes the class definition. yii\di\Container
resolveDependencies() Resolves dependencies by replacing them with the actual object instances. yii\di\Container

Method Details

build() protected method

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.

protected object build ( $class, $params, $config )
$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

throws yii\di\NotInstantiableException

If resolved to an abstract class or an interface (since 2.0.9)

clear() public method

Removes the definition for the specified name.

public void clear ( $class )
$class string

Class name, interface name or alias name

get() public method

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.

public object get ( $class, $params = [], $config = [] )
$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.

throws yii\base\InvalidConfigException

if the class cannot be recognized or correspond to an invalid definition

throws yii\di\NotInstantiableException

If resolved to an abstract class or an interface (since 2.0.9)

getDefinitions() public method

Returns the list of the object definitions or the loaded shared objects.

public array getDefinitions ( )
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 array getDependencies ( $class )
$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 boolean has ( $class )
$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 boolean hasSingleton ( $class, $checkInstance false )
$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 (available since version 2.0.7)

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:

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

public mixed invoke ( callable $callback, $params = [] )
$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.

throws yii\base\InvalidConfigException

if a dependency cannot be resolved or if a dependency cannot be fulfilled.

throws yii\di\NotInstantiableException

If resolved to an abstract class or an interface (since 2.0.9)

mergeParams() protected method

Merges the user-specified constructor parameters with the ones registered via set().

protected array mergeParams ( $class, $params )
$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 array normalizeDefinition ( $class, $definition )
$class string

Class name

$definition string|array|callable

The class definition

return array

The normalized class definition

throws yii\base\InvalidConfigException

if the definition is invalid.

resolveCallableDependencies() public method (available since version 2.0.7)

Resolve dependencies for a function.

This method can be used to implement similar functionality as provided by invoke() in other components.

public array resolveCallableDependencies ( callable $callback, $params = [] )
$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.

throws yii\base\InvalidConfigException

if a dependency cannot be resolved or if a dependency cannot be fulfilled.

throws yii\di\NotInstantiableException

If resolved to an abstract class or an interface (since 2.0.9)

resolveDependencies() protected method

Resolves dependencies by replacing them with the actual object instances.

protected array resolveDependencies ( $dependencies, $reflection null )
$dependencies array

The dependencies

$reflection ReflectionClass

The class reflection associated with the dependencies

return array

The resolved dependencies

throws yii\base\InvalidConfigException

if a dependency cannot be resolved or if a dependency cannot be fulfilled.

set() public method

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

public $this set ( $class, $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.

return $this

The container itself

setDefinitions() public method (available since version 2.0.11)

Registers class definitions within this container.

See also set() to know more about possible values of definitions.

public void 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

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.

See also set().

public $this setSingleton ( $class, $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.

return $this

The container itself

setSingletons() public method (available since version 2.0.11)

Registers class definitions as singletons within this container by calling setSingleton().

See also:

public void setSingletons ( array $singletons )
$singletons array

Array of singleton definitions. See setDefinitions() for allowed formats of array.