Class yii\di\Container
Inheritance | yii\di\Container » yii\base\Component » yii\base\BaseObject |
---|---|
Implements | yii\base\Configurable |
Available since version | 2.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 Properties
Property | Type | Description | Defined By |
---|---|---|---|
$behaviors | yii\base\Behavior[] | List of behaviors attached to this component. This property is read-only. | yii\base\Component |
$definitions | array | The list of the object definitions or the loaded shared objects (type or ID => definition or instance). This property is read-only. | yii\di\Container |
$resolveArrays | boolean | Whether to attempt to resolve elements in array dependencies. This property is write-only. | yii\di\Container |
$singleton | string | Class name, interface name or alias name | yii\di\Container |
$singletons | array | Array of singleton definitions. | yii\di\Container |
Public Methods
Method | Description | Defined 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 |
setResolveArrays() | 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
Method | Description | Defined 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 |
Property Details
The list of the object definitions or the loaded shared objects (type or ID => definition or instance). This property is read-only.
Whether to attempt to resolve elements in array dependencies. This property is write-only.
Class name, interface name or alias name
Array of singleton definitions. See setDefinitions() for allowed formats of array.
Method Details
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) |
Removes the definition for the specified name.
public void clear ( $class ) | ||
$class | string | Class name, interface name or alias name |
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|yii\di\Instance | The class Instance, name or an alias name (e.g. |
$params | array | A list of constructor parameter values. Use one of two definitions:
|
$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) |
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). |
---|
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. |
---|---|---|
throws | yii\di\NotInstantiableException | if a dependency cannot be resolved or if a dependency cannot be fulfilled. |
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.. |
---|
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 |
---|
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) |
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 |
---|
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. |
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) |
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. |
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
|
$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 |
---|
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:
Example:
]);
The second format:
Example:
]);
|
public void setResolveArrays ( $value ) | ||
$value | boolean | Whether to attempt to resolve elements in array dependencies |
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 |
$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 |
---|
Registers class definitions as singletons within this container by calling setSingleton().
See also:
- setDefinitions() for allowed formats of $singletons parameter.
- setSingleton() to know more about possible values of definitions.
public void setSingletons ( array $singletons ) | ||
$singletons | array | Array of singleton definitions. See setDefinitions() for allowed formats of array. |