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. 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.
Public Properties
Property | Type | Description | Defined By |
---|---|---|---|
$behaviors | yii\base\Behavior[] | List of behaviors attached to this component. | yii\base\Component |
$definitions | array | The list of the object definitions or the loaded shared objects (type or ID => definition or instance). | yii\di\Container |
$resolveArrays | boolean | Whether to attempt to resolve elements in array dependencies. | 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).
Whether to attempt to resolve elements in array dependencies.
Class name, interface name or alias name
Array of singleton definitions. See setDefinitions() for allowed formats of array.
Method Details
Defined in: yii\base\Component::__call()
Calls the named method which is not a class method.
This method will check if any attached behavior has the named method and will execute it if available.
Do not call this method directly as it is a PHP magic method that will be implicitly called when an unknown method is being invoked.
public mixed __call ( $name, $params ) | ||
$name | string |
The method name |
$params | array |
Method parameters |
return | mixed |
The method return value |
---|---|---|
throws | yii\base\UnknownMethodException |
when calling unknown method |
public function __call($name, $params)
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $object) {
if ($object->hasMethod($name)) {
return call_user_func_array([$object, $name], $params);
}
}
throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}
Defined in: yii\base\Component::__clone()
This method is called after the object is created by cloning an existing one.
It removes all behaviors because they are attached to the old object.
public void __clone ( ) |
public function __clone()
{
$this->_events = [];
$this->_eventWildcards = [];
$this->_behaviors = null;
}
Defined in: yii\base\BaseObject::__construct()
Constructor.
The default implementation does two things:
- Initializes the object with the given configuration
$config
. - Call init().
If this method is overridden in a child class, it is recommended that
- the last parameter of the constructor is a configuration array, like
$config
here. - call the parent implementation at the end of the constructor.
public void __construct ( $config = [] ) | ||
$config | array |
Name-value pairs that will be used to initialize the object properties |
public function __construct($config = [])
{
if (!empty($config)) {
Yii::configure($this, $config);
}
$this->init();
}
Defined in: yii\base\Component::__get()
Returns the value of a component property.
This method will check in the following order and act accordingly:
- a property defined by a getter: return the getter result
- a property of a behavior: return the behavior property value
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing $value = $component->property;
.
See also __set().
public mixed __get ( $name ) | ||
$name | string |
The property name |
return | mixed |
The property value or the value of a behavior's property |
---|---|---|
throws | yii\base\UnknownPropertyException |
if the property is not defined |
throws | yii\base\InvalidCallException |
if the property is write-only. |
public function __get($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
// read property, e.g. getName()
return $this->$getter();
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name)) {
return $behavior->$name;
}
}
if (method_exists($this, 'set' . $name)) {
throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}
Defined in: yii\base\Component::__isset()
Checks if a property is set, i.e. defined and not null.
This method will check in the following order and act accordingly:
- a property defined by a setter: return whether the property is set
- a property of a behavior: return whether the property is set
- return
false
for non existing properties
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing isset($component->property)
.
public boolean __isset ( $name ) | ||
$name | string |
The property name or the event name |
return | boolean |
Whether the named property is set |
---|
public function __isset($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
return $this->$getter() !== null;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name)) {
return $behavior->$name !== null;
}
}
return false;
}
Defined in: yii\base\Component::__set()
Sets the value of a component property.
This method will check in the following order and act accordingly:
- a property defined by a setter: set the property value
- an event in the format of "on xyz": attach the handler to the event "xyz"
- a behavior in the format of "as xyz": attach the behavior named as "xyz"
- a property of a behavior: set the behavior property value
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing $component->property = $value;
.
See also __get().
public void __set ( $name, $value ) | ||
$name | string |
The property name or the event name |
$value | mixed |
The property value |
throws | yii\base\UnknownPropertyException |
if the property is not defined |
---|---|---|
throws | yii\base\InvalidCallException |
if the property is read-only. |
public function __set($name, $value)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
// set property
$this->$setter($value);
return;
} elseif (strncmp($name, 'on ', 3) === 0) {
// on event: attach event handler
$this->on(trim(substr($name, 3)), $value);
return;
} elseif (strncmp($name, 'as ', 3) === 0) {
// as behavior: attach behavior
$name = trim(substr($name, 3));
$this->attachBehavior($name, $value instanceof Behavior ? $value : Yii::createObject($value));
return;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name)) {
$behavior->$name = $value;
return;
}
}
if (method_exists($this, 'get' . $name)) {
throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
}
Defined in: yii\base\Component::__unset()
Sets a component property to be null.
This method will check in the following order and act accordingly:
- a property defined by a setter: set the property value to be null
- a property of a behavior: set the property value to be null
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing unset($component->property)
.
public void __unset ( $name ) | ||
$name | string |
The property name |
throws | yii\base\InvalidCallException |
if the property is read only. |
---|
public function __unset($name)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
$this->$setter(null);
return;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name)) {
$behavior->$name = null;
return;
}
}
throw new InvalidCallException('Unsetting an unknown or read-only property: ' . get_class($this) . '::' . $name);
}
Defined in: yii\base\Component::attachBehavior()
Attaches a behavior to this component.
This method will create the behavior object based on the given configuration. After that, the behavior object will be attached to this component by calling the yii\base\Behavior::attach() method.
See also detachBehavior().
public yii\base\Behavior attachBehavior ( $name, $behavior ) | ||
$name | string |
The name of the behavior. |
$behavior | string|array|yii\base\Behavior |
The behavior configuration. This can be one of the following:
|
return | yii\base\Behavior |
The behavior object |
---|
public function attachBehavior($name, $behavior)
{
$this->ensureBehaviors();
return $this->attachBehaviorInternal($name, $behavior);
}
Defined in: yii\base\Component::attachBehaviors()
Attaches a list of behaviors to the component.
Each behavior is indexed by its name and should be a yii\base\Behavior object, a string specifying the behavior class, or an configuration array for creating the behavior.
See also attachBehavior().
public void attachBehaviors ( $behaviors ) | ||
$behaviors | array |
List of behaviors to be attached to the component |
public function attachBehaviors($behaviors)
{
$this->ensureBehaviors();
foreach ($behaviors as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
Defined in: yii\base\Component::behaviors()
Returns a list of behaviors that this component should behave as.
Child classes may override this method to specify the behaviors they want to behave as.
The return value of this method should be an array of behavior objects or configurations indexed by behavior names. A behavior configuration can be either a string specifying the behavior class or an array of the following structure:
'behaviorName' => [
'class' => 'BehaviorClass',
'property1' => 'value1',
'property2' => 'value2',
]
Note that a behavior class must extend from yii\base\Behavior. Behaviors can be attached using a name or anonymously. When a name is used as the array key, using this name, the behavior can later be retrieved using getBehavior() or be detached using detachBehavior(). Anonymous behaviors can not be retrieved or detached.
Behaviors declared in this method will be attached to the component automatically (on demand).
public array behaviors ( ) | ||
return | array |
The behavior configurations. |
---|
public function behaviors()
{
return [];
}
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) |
protected function build($class, $params, $config)
{
/* @var $reflection ReflectionClass */
list($reflection, $dependencies) = $this->getDependencies($class);
$addDependencies = [];
if (isset($config['__construct()'])) {
$addDependencies = $config['__construct()'];
unset($config['__construct()']);
}
foreach ($params as $index => $param) {
$addDependencies[$index] = $param;
}
$this->validateDependencies($addDependencies);
if ($addDependencies && is_int(key($addDependencies))) {
$dependencies = array_values($dependencies);
$dependencies = $this->mergeDependencies($dependencies, $addDependencies);
} else {
$dependencies = $this->mergeDependencies($dependencies, $addDependencies);
$dependencies = array_values($dependencies);
}
$dependencies = $this->resolveDependencies($dependencies, $reflection);
if (!$reflection->isInstantiable()) {
throw new NotInstantiableException($reflection->name);
}
if (empty($config)) {
return $reflection->newInstanceArgs($dependencies);
}
$config = $this->resolveDependencies($config);
if (!empty($dependencies) && $reflection->implementsInterface('yii\base\Configurable')) {
// set $config as the last parameter (existing one will be overwritten)
$dependencies[count($dependencies) - 1] = $config;
return $reflection->newInstanceArgs($dependencies);
}
$object = $reflection->newInstanceArgs($dependencies);
foreach ($config as $name => $value) {
$object->$name = $value;
}
return $object;
}
Defined in: yii\base\Component::canGetProperty()
Returns a value indicating whether a property can be read.
A property can be read if:
- the class has a getter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVars
is true); - an attached behavior has a readable property of the given name (when
$checkBehaviors
is true).
See also canSetProperty().
public boolean canGetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
The property name |
$checkVars | boolean |
Whether to treat member variables as properties |
$checkBehaviors | boolean |
Whether to treat behaviors' properties as properties of this component |
return | boolean |
Whether the property can be read |
---|
public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if (method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name, $checkVars)) {
return true;
}
}
}
return false;
}
Defined in: yii\base\Component::canSetProperty()
Returns a value indicating whether a property can be set.
A property can be written if:
- the class has a setter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVars
is true); - an attached behavior has a writable property of the given name (when
$checkBehaviors
is true).
See also canGetProperty().
public boolean canSetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
The property name |
$checkVars | boolean |
Whether to treat member variables as properties |
$checkBehaviors | boolean |
Whether to treat behaviors' properties as properties of this component |
return | boolean |
Whether the property can be written |
---|
public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if (method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name, $checkVars)) {
return true;
}
}
}
return false;
}
::class
instead.
Defined in: yii\base\BaseObject::className()
Returns the fully qualified name of this class.
public static string className ( ) | ||
return | string |
The fully qualified name of this class. |
---|
public static function className()
{
return get_called_class();
}
Removes the definition for the specified name.
public void clear ( $class ) | ||
$class | string |
Class name, interface name or alias name |
public function clear($class)
{
unset($this->_definitions[$class], $this->_singletons[$class]);
}
Defined in: yii\base\Component::detachBehavior()
Detaches a behavior from the component.
The behavior's yii\base\Behavior::detach() method will be invoked.
public yii\base\Behavior|null detachBehavior ( $name ) | ||
$name | string |
The behavior's name. |
return | yii\base\Behavior|null |
The detached behavior. Null if the behavior does not exist. |
---|
public function detachBehavior($name)
{
$this->ensureBehaviors();
if (isset($this->_behaviors[$name])) {
$behavior = $this->_behaviors[$name];
unset($this->_behaviors[$name]);
$behavior->detach();
return $behavior;
}
return null;
}
Defined in: yii\base\Component::detachBehaviors()
Detaches all behaviors from the component.
public void detachBehaviors ( ) |
public function detachBehaviors()
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $name => $behavior) {
$this->detachBehavior($name);
}
}
Defined in: yii\base\Component::ensureBehaviors()
Makes sure that the behaviors declared in behaviors() are attached to this component.
public void ensureBehaviors ( ) |
public function ensureBehaviors()
{
if ($this->_behaviors === null) {
$this->_behaviors = [];
foreach ($this->behaviors() as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
}
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) |
public function get($class, $params = [], $config = [])
{
if ($class instanceof Instance) {
$class = $class->id;
}
if (isset($this->_singletons[$class])) {
// singleton
return $this->_singletons[$class];
} elseif (!isset($this->_definitions[$class])) {
return $this->build($class, $params, $config);
}
$definition = $this->_definitions[$class];
if (is_callable($definition, true)) {
$params = $this->resolveDependencies($this->mergeParams($class, $params));
$object = call_user_func($definition, $this, $params, $config);
} elseif (is_array($definition)) {
$concrete = $definition['class'];
unset($definition['class']);
$config = array_merge($definition, $config);
$params = $this->mergeParams($class, $params);
if ($concrete === $class) {
$object = $this->build($class, $params, $config);
} else {
$object = $this->get($concrete, $params, $config);
}
} elseif (is_object($definition)) {
return $this->_singletons[$class] = $definition;
} else {
throw new InvalidConfigException('Unexpected object definition type: ' . gettype($definition));
}
if (array_key_exists($class, $this->_singletons)) {
// singleton
$this->_singletons[$class] = $object;
}
return $object;
}
Defined in: yii\base\Component::getBehavior()
Returns the named behavior object.
public yii\base\Behavior|null getBehavior ( $name ) | ||
$name | string |
The behavior name |
return | yii\base\Behavior|null |
The behavior object, or null if the behavior does not exist |
---|
public function getBehavior($name)
{
$this->ensureBehaviors();
return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
}
Defined in: yii\base\Component::getBehaviors()
Returns all behaviors attached to this component.
public yii\base\Behavior[] getBehaviors ( ) | ||
return | yii\base\Behavior[] |
List of behaviors attached to this component |
---|
public function getBehaviors()
{
$this->ensureBehaviors();
return $this->_behaviors;
}
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). |
---|
public function getDefinitions()
{
return $this->_definitions;
}
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. |
protected function getDependencies($class)
{
if (isset($this->_reflections[$class])) {
return [$this->_reflections[$class], $this->_dependencies[$class]];
}
$dependencies = [];
try {
$reflection = new ReflectionClass($class);
} catch (\ReflectionException $e) {
throw new NotInstantiableException(
$class,
'Failed to instantiate component or class "' . $class . '".',
0,
$e
);
}
$constructor = $reflection->getConstructor();
if ($constructor !== null) {
foreach ($constructor->getParameters() as $param) {
if (PHP_VERSION_ID >= 50600 && $param->isVariadic()) {
break;
}
if (PHP_VERSION_ID >= 80000) {
$c = $param->getType();
$isClass = false;
if ($c instanceof ReflectionNamedType) {
$isClass = !$c->isBuiltin();
}
} else {
try {
$c = $param->getClass();
} catch (ReflectionException $e) {
if (!$this->isNulledParam($param)) {
$notInstantiableClass = null;
if (PHP_VERSION_ID >= 70000) {
$type = $param->getType();
if ($type instanceof ReflectionNamedType) {
$notInstantiableClass = $type->getName();
}
}
throw new NotInstantiableException(
$notInstantiableClass,
$notInstantiableClass === null ? 'Can not instantiate unknown class.' : null
);
} else {
$c = null;
}
}
$isClass = $c !== null;
}
$className = $isClass ? $c->getName() : null;
if ($className !== null) {
$dependencies[$param->getName()] = Instance::of($className, $this->isNulledParam($param));
} else {
$dependencies[$param->getName()] = $param->isDefaultValueAvailable()
? $param->getDefaultValue()
: null;
}
}
}
$this->_reflections[$class] = $reflection;
$this->_dependencies[$class] = $dependencies;
return [$reflection, $dependencies];
}
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. |
---|
public function has($class)
{
return isset($this->_definitions[$class]);
}
Defined in: yii\base\Component::hasEventHandlers()
Returns a value indicating whether there is any handler attached to the named event.
public boolean hasEventHandlers ( $name ) | ||
$name | string |
The event name |
return | boolean |
Whether there is any handler attached to the event. |
---|
public function hasEventHandlers($name)
{
$this->ensureBehaviors();
if (!empty($this->_events[$name])) {
return true;
}
foreach ($this->_eventWildcards as $wildcard => $handlers) {
if (!empty($handlers) && StringHelper::matchWildcard($wildcard, $name)) {
return true;
}
}
return Event::hasHandlers($this, $name);
}
Defined in: yii\base\Component::hasMethod()
Returns a value indicating whether a method is defined.
A method is defined if:
- the class has a method with the specified name
- an attached behavior has a method with the given name (when
$checkBehaviors
is true).
public boolean hasMethod ( $name, $checkBehaviors = true ) | ||
$name | string |
The property name |
$checkBehaviors | boolean |
Whether to treat behaviors' methods as methods of this component |
return | boolean |
Whether the method is defined |
---|
public function hasMethod($name, $checkBehaviors = true)
{
if (method_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->hasMethod($name)) {
return true;
}
}
}
return false;
}
Defined in: yii\base\Component::hasProperty()
Returns a value indicating whether a property is defined for this component.
A property is defined if:
- the class has a getter or setter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVars
is true); - an attached behavior has a property of the given name (when
$checkBehaviors
is true).
See also:
public boolean hasProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
The property name |
$checkVars | boolean |
Whether to treat member variables as properties |
$checkBehaviors | boolean |
Whether to treat behaviors' properties as properties of this component |
return | boolean |
Whether the property is defined |
---|
public function hasProperty($name, $checkVars = true, $checkBehaviors = true)
{
return $this->canGetProperty($name, $checkVars, $checkBehaviors) || $this->canSetProperty($name, false, $checkBehaviors);
}
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 |
---|
public function hasSingleton($class, $checkInstance = false)
{
return $checkInstance ? isset($this->_singletons[$class]) : array_key_exists($class, $this->_singletons);
}
Defined in: yii\base\BaseObject::init()
Initializes the object.
This method is invoked at the end of the constructor after the object is initialized with the given configuration.
public void init ( ) |
public function init()
{
}
Invoke 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.
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) |
public function invoke(callable $callback, $params = [])
{
return call_user_func_array($callback, $this->resolveCallableDependencies($callback, $params));
}
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 |
---|
protected function mergeParams($class, $params)
{
if (empty($this->_params[$class])) {
return $params;
} elseif (empty($params)) {
return $this->_params[$class];
}
$ps = $this->_params[$class];
foreach ($params as $index => $value) {
$ps[$index] = $value;
}
return $ps;
}
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. |
protected function normalizeDefinition($class, $definition)
{
if (empty($definition)) {
return ['class' => $class];
} elseif (is_string($definition)) {
return ['class' => $definition];
} elseif ($definition instanceof Instance) {
return ['class' => $definition->id];
} elseif (is_callable($definition, true) || is_object($definition)) {
return $definition;
} elseif (is_array($definition)) {
if (!isset($definition['class']) && isset($definition['__class'])) {
$definition['class'] = $definition['__class'];
unset($definition['__class']);
}
if (!isset($definition['class'])) {
if (strpos($class, '\\') !== false) {
$definition['class'] = $class;
} else {
throw new InvalidConfigException('A class definition requires a "class" member.');
}
}
return $definition;
}
throw new InvalidConfigException("Unsupported definition type for \"$class\": " . gettype($definition));
}
Defined in: yii\base\Component::off()
Detaches an existing event handler from this component.
This method is the opposite of on().
Note: in case wildcard pattern is passed for event name, only the handlers registered with this wildcard will be removed, while handlers registered with plain names matching this wildcard will remain.
See also on().
public boolean off ( $name, $handler = null ) | ||
$name | string |
Event name |
$handler | callable|null |
The event handler to be removed. If it is null, all handlers attached to the named event will be removed. |
return | boolean |
If a handler is found and detached |
---|
public function off($name, $handler = null)
{
$this->ensureBehaviors();
if (empty($this->_events[$name]) && empty($this->_eventWildcards[$name])) {
return false;
}
if ($handler === null) {
unset($this->_events[$name], $this->_eventWildcards[$name]);
return true;
}
$removed = false;
// plain event names
if (isset($this->_events[$name])) {
foreach ($this->_events[$name] as $i => $event) {
if ($event[0] === $handler) {
unset($this->_events[$name][$i]);
$removed = true;
}
}
if ($removed) {
$this->_events[$name] = array_values($this->_events[$name]);
return true;
}
}
// wildcard event names
if (isset($this->_eventWildcards[$name])) {
foreach ($this->_eventWildcards[$name] as $i => $event) {
if ($event[0] === $handler) {
unset($this->_eventWildcards[$name][$i]);
$removed = true;
}
}
if ($removed) {
$this->_eventWildcards[$name] = array_values($this->_eventWildcards[$name]);
// remove empty wildcards to save future redundant regex checks:
if (empty($this->_eventWildcards[$name])) {
unset($this->_eventWildcards[$name]);
}
}
}
return $removed;
}
Defined in: yii\base\Component::on()
Attaches an event handler to an event.
The event handler must be a valid PHP callback. The following are some examples:
function ($event) { ... } // anonymous function
[$object, 'handleClick'] // $object->handleClick()
['Page', 'handleClick'] // Page::handleClick()
'handleClick' // global function handleClick()
The event handler must be defined with the following signature,
function ($event)
where $event
is an yii\base\Event object which includes parameters associated with the event.
Since 2.0.14 you can specify event name as a wildcard pattern:
$component->on('event.group.*', function ($event) {
Yii::trace($event->name . ' is triggered.');
});
See also off().
public void on ( $name, $handler, $data = null, $append = true ) | ||
$name | string |
The event name |
$handler | callable |
The event handler |
$data | mixed |
The data to be passed to the event handler when the event is triggered. When the event handler is invoked, this data can be accessed via yii\base\Event::$data. |
$append | boolean |
Whether to append new event handler to the end of the existing handler list. If false, the new handler will be inserted at the beginning of the existing handler list. |
public function on($name, $handler, $data = null, $append = true)
{
$this->ensureBehaviors();
if (strpos($name, '*') !== false) {
if ($append || empty($this->_eventWildcards[$name])) {
$this->_eventWildcards[$name][] = [$handler, $data];
} else {
array_unshift($this->_eventWildcards[$name], [$handler, $data]);
}
return;
}
if ($append || empty($this->_events[$name])) {
$this->_events[$name][] = [$handler, $data];
} else {
array_unshift($this->_events[$name], [$handler, $data]);
}
}
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) |
public function resolveCallableDependencies(callable $callback, $params = [])
{
if (is_array($callback)) {
$reflection = new \ReflectionMethod($callback[0], $callback[1]);
} elseif (is_object($callback) && !$callback instanceof \Closure) {
$reflection = new \ReflectionMethod($callback, '__invoke');
} else {
$reflection = new \ReflectionFunction($callback);
}
$args = [];
$associative = ArrayHelper::isAssociative($params);
foreach ($reflection->getParameters() as $param) {
$name = $param->getName();
if (PHP_VERSION_ID >= 80000) {
$class = $param->getType();
if ($class instanceof \ReflectionUnionType || (PHP_VERSION_ID >= 80100 && $class instanceof \ReflectionIntersectionType)) {
$isClass = false;
foreach ($class->getTypes() as $type) {
if (!$type->isBuiltin()) {
$class = $type;
$isClass = true;
break;
}
}
} else {
$isClass = $class !== null && !$class->isBuiltin();
}
} else {
$class = $param->getClass();
$isClass = $class !== null;
}
if ($isClass) {
$className = $class->getName();
if (PHP_VERSION_ID >= 50600 && $param->isVariadic()) {
$args = array_merge($args, array_values($params));
break;
}
if ($associative && isset($params[$name]) && $params[$name] instanceof $className) {
$args[] = $params[$name];
unset($params[$name]);
} elseif (!$associative && isset($params[0]) && $params[0] instanceof $className) {
$args[] = array_shift($params);
} elseif (isset(Yii::$app) && Yii::$app->has($name) && ($obj = Yii::$app->get($name)) instanceof $className) {
$args[] = $obj;
} else {
// If the argument is optional we catch not instantiable exceptions
try {
$args[] = $this->get($className);
} catch (NotInstantiableException $e) {
if ($param->isDefaultValueAvailable()) {
$args[] = $param->getDefaultValue();
} else {
throw $e;
}
}
}
} elseif ($associative && isset($params[$name])) {
$args[] = $params[$name];
unset($params[$name]);
} elseif (!$associative && count($params)) {
$args[] = array_shift($params);
} elseif ($param->isDefaultValueAvailable()) {
$args[] = $param->getDefaultValue();
} elseif (!$param->isOptional()) {
$funcName = $reflection->getName();
throw new InvalidConfigException("Missing required parameter \"$name\" when calling \"$funcName\".");
}
}
foreach ($params as $value) {
$args[] = $value;
}
return $args;
}
Resolves dependencies by replacing them with the actual object instances.
protected array resolveDependencies ( $dependencies, $reflection = null ) | ||
$dependencies | array |
The dependencies |
$reflection | ReflectionClass|null |
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. |
protected function resolveDependencies($dependencies, $reflection = null)
{
foreach ($dependencies as $index => $dependency) {
if ($dependency instanceof Instance) {
if ($dependency->id !== null) {
$dependencies[$index] = $dependency->get($this);
} elseif ($reflection !== null) {
$name = $reflection->getConstructor()->getParameters()[$index]->getName();
$class = $reflection->getName();
throw new InvalidConfigException("Missing required parameter \"$name\" when instantiating \"$class\".");
}
} elseif ($this->_resolveArrays && is_array($dependency)) {
$dependencies[$index] = $this->resolveDependencies($dependency, $reflection);
}
}
return $dependencies;
}
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 |
---|
public function set($class, $definition = [], array $params = [])
{
$this->_definitions[$class] = $this->normalizeDefinition($class, $definition);
$this->_params[$class] = $params;
unset($this->_singletons[$class]);
return $this;
}
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 function setDefinitions(array $definitions)
{
foreach ($definitions as $class => $definition) {
if (is_array($definition) && count($definition) === 2 && array_values($definition) === $definition && is_array($definition[1])) {
$this->set($class, $definition[0], $definition[1]);
continue;
}
$this->set($class, $definition);
}
}
public void setResolveArrays ( $value ) | ||
$value | boolean |
Whether to attempt to resolve elements in array dependencies |
public function setResolveArrays($value)
{
$this->_resolveArrays = (bool) $value;
}
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 |
---|
public function setSingleton($class, $definition = [], array $params = [])
{
$this->_definitions[$class] = $this->normalizeDefinition($class, $definition);
$this->_params[$class] = $params;
$this->_singletons[$class] = null;
return $this;
}
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. |
public function setSingletons(array $singletons)
{
foreach ($singletons as $class => $definition) {
if (is_array($definition) && count($definition) === 2 && array_values($definition) === $definition) {
$this->setSingleton($class, $definition[0], $definition[1]);
continue;
}
$this->setSingleton($class, $definition);
}
}
Defined in: yii\base\Component::trigger()
Triggers an event.
This method represents the happening of an event. It invokes all attached handlers for the event including class-level handlers.
public void trigger ( $name, yii\base\Event $event = null ) | ||
$name | string |
The event name |
$event | yii\base\Event|null |
The event instance. If not set, a default yii\base\Event object will be created. |
public function trigger($name, Event $event = null)
{
$this->ensureBehaviors();
$eventHandlers = [];
foreach ($this->_eventWildcards as $wildcard => $handlers) {
if (StringHelper::matchWildcard($wildcard, $name)) {
$eventHandlers[] = $handlers;
}
}
if (!empty($this->_events[$name])) {
$eventHandlers[] = $this->_events[$name];
}
if (!empty($eventHandlers)) {
$eventHandlers = call_user_func_array('array_merge', $eventHandlers);
if ($event === null) {
$event = new Event();
}
if ($event->sender === null) {
$event->sender = $this;
}
$event->handled = false;
$event->name = $name;
foreach ($eventHandlers as $handler) {
$event->data = $handler[1];
call_user_func($handler[0], $event);
// stop further handling if the event is handled
if ($event->handled) {
return;
}
}
}
// invoke class-level attached handlers
Event::trigger($this, $name, $event);
}