ServiceLocator
extends Component
in package
ServiceLocator implements a [service locator](https://en.wikipedia.org/wiki/Service_locator_pattern).
To use ServiceLocator, you first need to register component IDs with the corresponding component definitions with the locator by calling [[set()]] or [[setComponents()]]. You can then call [[get()]] to retrieve a component with the specified ID. The locator will automatically instantiate and configure the component according to the definition.
For example,
$locator = new \yii\di\ServiceLocator;
$locator->setComponents([
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'sqlite:path/to/file.db',
],
'cache' => [
'class' => 'yii\caching\DbCache',
'db' => 'db',
],
]);
$db = $locator->get('db'); // or $locator->db
$cache = $locator->get('cache'); // or $locator->cache
Because [[\yii\base\Module]] extends from ServiceLocator, modules and the application are all service locators. Modules add tree traversal for service resolution.
For more details and usage information on ServiceLocator, see the guide article on service locators.
Tags
Table of Contents
Properties
- $behaviors : array<string|int, Behavior>
- $components : array<string|int, mixed>
- $_behaviors : array<string|int, Behavior>|null
- $_components : array<string|int, mixed>
- $_definitions : array<string|int, mixed>
- $_events : array<string|int, mixed>
- $_eventWildcards : array<string|int, mixed>
Methods
- __call() : mixed
- Calls the named method which is not a class method.
- __clone() : mixed
- This method is called after the object is created by cloning an existing one.
- __construct() : mixed
- Constructor.
- __get() : mixed
- Getter magic method.
- __isset() : bool
- Checks if a property value is null.
- __set() : mixed
- Sets the value of a component property.
- __unset() : mixed
- Sets a component property to be null.
- attachBehavior() : Behavior
- Attaches a behavior to this component.
- attachBehaviors() : mixed
- Attaches a list of behaviors to the component.
- behaviors() : array<string|int, mixed>
- Returns a list of behaviors that this component should behave as.
- canGetProperty() : bool
- Returns a value indicating whether a property can be read.
- canSetProperty() : bool
- Returns a value indicating whether a property can be set.
- className() : string
- Returns the fully qualified name of this class.
- clear() : mixed
- Removes the component from the locator.
- detachBehavior() : Behavior|null
- Detaches a behavior from the component.
- detachBehaviors() : mixed
- Detaches all behaviors from the component.
- ensureBehaviors() : mixed
- Makes sure that the behaviors declared in [[behaviors()]] are attached to this component.
- get() : object|null
- Returns the component instance with the specified ID.
- getBehavior() : Behavior|null
- Returns the named behavior object.
- getBehaviors() : array<string|int, Behavior>
- Returns all behaviors attached to this component.
- getComponents() : array<string|int, mixed>
- Returns the list of the component definitions or the loaded component instances.
- has() : bool
- Returns a value indicating whether the locator has the specified component definition or has instantiated the component.
- hasEventHandlers() : bool
- Returns a value indicating whether there is any handler attached to the named event.
- hasMethod() : bool
- Returns a value indicating whether a method is defined.
- hasProperty() : bool
- Returns a value indicating whether a property is defined for this component.
- init() : mixed
- Initializes the object.
- off() : bool
- Detaches an existing event handler from this component.
- on() : mixed
- Attaches an event handler to an event.
- set() : mixed
- Registers a component definition with this locator.
- setComponents() : mixed
- Registers a set of component definitions in this locator.
- trigger() : mixed
- Triggers an event.
- attachBehaviorInternal() : Behavior
- Attaches a behavior to this component.
Properties
$behaviors read-only
public
array<string|int, Behavior>
$behaviors
List of behaviors attached to this component.
$components
public
array<string|int, mixed>
$components
The list of the component definitions or the loaded component instances (ID => definition or instance).
$_behaviors
private
array<string|int, Behavior>|null
$_behaviors
the attached behaviors (behavior name => behavior). This is null
when not initialized.
$_components
private
array<string|int, mixed>
$_components
= []
shared component instances indexed by their IDs
$_definitions
private
array<string|int, mixed>
$_definitions
= []
component definitions indexed by their IDs
$_events
private
array<string|int, mixed>
$_events
= []
the attached event handlers (event name => handlers)
$_eventWildcards
private
array<string|int, mixed>
$_eventWildcards
= []
the event handlers attached for wildcard patterns (event name wildcard => handlers)
Tags
Methods
__call()
Calls the named method which is not a class method.
public
__call(string $name, array<string|int, mixed> $params) : mixed
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.
Parameters
- $name : string
-
the method name
- $params : array<string|int, mixed>
-
method parameters
Tags
Return values
mixed —the method return value
__clone()
This method is called after the object is created by cloning an existing one.
public
__clone() : mixed
It removes all behaviors because they are attached to the old object.
__construct()
Constructor.
public
__construct([array<string|int, mixed> $config = [] ]) : mixed
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.
Parameters
- $config : array<string|int, mixed> = []
-
name-value pairs that will be used to initialize the object properties
__get()
Getter magic method.
public
__get(string $name) : mixed
This method is overridden to support accessing components like reading properties.
Parameters
- $name : string
-
component or property name
Return values
mixed —the named property value
__isset()
Checks if a property value is null.
public
__isset(string $name) : bool
This method overrides the parent implementation by checking if the named component is loaded.
Parameters
- $name : string
-
the property name or the event name
Return values
bool —whether the property value is null
__set()
Sets the value of a component property.
public
__set(string $name, mixed $value) : mixed
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;
.
Parameters
- $name : string
-
the property name or the event name
- $value : mixed
-
the property value
Tags
__unset()
Sets a component property to be null.
public
__unset(string $name) : mixed
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)
.
Parameters
- $name : string
-
the property name
Tags
attachBehavior()
Attaches a behavior to this component.
public
attachBehavior(string $name, string|array<string|int, mixed>|Behavior $behavior) : Behavior
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 [[Behavior::attach()]] method.
Parameters
- $name : string
-
the name of the behavior.
- $behavior : string|array<string|int, mixed>|Behavior
-
the behavior configuration. This can be one of the following:
- a [[Behavior]] object
- a string specifying the behavior class
- an object configuration array that will be passed to [[Yii::createObject()]] to create the behavior object.
Tags
Return values
Behavior —the behavior object
attachBehaviors()
Attaches a list of behaviors to the component.
public
attachBehaviors(array<string|int, mixed> $behaviors) : mixed
Each behavior is indexed by its name and should be a [[Behavior]] object, a string specifying the behavior class, or an configuration array for creating the behavior.
Parameters
- $behaviors : array<string|int, mixed>
-
list of behaviors to be attached to the component
Tags
behaviors()
Returns a list of behaviors that this component should behave as.
public
behaviors() : array<string|int, mixed>
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 [[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).
Return values
array<string|int, mixed> —the behavior configurations.
canGetProperty()
Returns a value indicating whether a property can be read.
public
canGetProperty(string $name[, bool $checkVars = true ][, bool $checkBehaviors = true ]) : bool
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).
Parameters
- $name : string
-
the property name
- $checkVars : bool = true
-
whether to treat member variables as properties
- $checkBehaviors : bool = true
-
whether to treat behaviors' properties as properties of this component
Tags
Return values
bool —whether the property can be read
canSetProperty()
Returns a value indicating whether a property can be set.
public
canSetProperty(string $name[, bool $checkVars = true ][, bool $checkBehaviors = true ]) : bool
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).
Parameters
- $name : string
-
the property name
- $checkVars : bool = true
-
whether to treat member variables as properties
- $checkBehaviors : bool = true
-
whether to treat behaviors' properties as properties of this component
Tags
Return values
bool —whether the property can be written
className()
Returns the fully qualified name of this class.
public
static className() : string
Tags
Return values
string —the fully qualified name of this class.
clear()
Removes the component from the locator.
public
clear(string $id) : mixed
Parameters
- $id : string
-
the component ID
detachBehavior()
Detaches a behavior from the component.
public
detachBehavior(string $name) : Behavior|null
The behavior's [[Behavior::detach()]] method will be invoked.
Parameters
- $name : string
-
the behavior's name.
Return values
Behavior|null —the detached behavior. Null if the behavior does not exist.
detachBehaviors()
Detaches all behaviors from the component.
public
detachBehaviors() : mixed
ensureBehaviors()
Makes sure that the behaviors declared in [[behaviors()]] are attached to this component.
public
ensureBehaviors() : mixed
get()
Returns the component instance with the specified ID.
public
get(string $id[, bool $throwException = true ]) : object|null
Parameters
- $id : string
-
component ID (e.g.
db
). - $throwException : bool = true
-
whether to throw an exception if
$id
is not registered with the locator before.
Tags
Return values
object|null —the component of the specified ID. If $throwException
is false and $id
is not registered before, null will be returned.
getBehavior()
Returns the named behavior object.
public
getBehavior(string $name) : Behavior|null
Parameters
- $name : string
-
the behavior name
Return values
Behavior|null —the behavior object, or null if the behavior does not exist
getBehaviors()
Returns all behaviors attached to this component.
public
getBehaviors() : array<string|int, Behavior>
Return values
array<string|int, Behavior> —list of behaviors attached to this component
getComponents()
Returns the list of the component definitions or the loaded component instances.
public
getComponents([bool $returnDefinitions = true ]) : array<string|int, mixed>
Parameters
- $returnDefinitions : bool = true
-
whether to return component definitions instead of the loaded component instances.
Return values
array<string|int, mixed> —the list of the component definitions or the loaded component instances (ID => definition or instance).
has()
Returns a value indicating whether the locator has the specified component definition or has instantiated the component.
public
has(string $id[, bool $checkInstance = false ]) : bool
This method may return different results depending on the value of $checkInstance
.
- If
$checkInstance
is false (default), the method will return a value indicating whether the locator has the specified component definition. - If
$checkInstance
is true, the method will return a value indicating whether the locator has instantiated the specified component.
Parameters
- $id : string
-
component ID (e.g.
db
). - $checkInstance : bool = false
-
whether the method should check if the component is shared and instantiated.
Tags
Return values
bool —whether the locator has the specified component definition or has instantiated the component.
hasEventHandlers()
Returns a value indicating whether there is any handler attached to the named event.
public
hasEventHandlers(string $name) : bool
Parameters
- $name : string
-
the event name
Return values
bool —whether there is any handler attached to the event.
hasMethod()
Returns a value indicating whether a method is defined.
public
hasMethod(string $name[, bool $checkBehaviors = true ]) : bool
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).
Parameters
- $name : string
-
the property name
- $checkBehaviors : bool = true
-
whether to treat behaviors' methods as methods of this component
Return values
bool —whether the method is defined
hasProperty()
Returns a value indicating whether a property is defined for this component.
public
hasProperty(string $name[, bool $checkVars = true ][, bool $checkBehaviors = true ]) : bool
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).
Parameters
- $name : string
-
the property name
- $checkVars : bool = true
-
whether to treat member variables as properties
- $checkBehaviors : bool = true
-
whether to treat behaviors' properties as properties of this component
Tags
Return values
bool —whether the property is defined
init()
Initializes the object.
public
init() : mixed
This method is invoked at the end of the constructor after the object is initialized with the given configuration.
off()
Detaches an existing event handler from this component.
public
off(string $name[, callable|null $handler = null ]) : bool
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.
Parameters
- $name : string
-
event name
- $handler : callable|null = null
-
the event handler to be removed. If it is null, all handlers attached to the named event will be removed.
Tags
Return values
bool —if a handler is found and detached
on()
Attaches an event handler to an event.
public
on(string $name, callable $handler[, mixed $data = null ][, bool $append = true ]) : mixed
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 [[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.');
});
Parameters
- $name : string
-
the event name
- $handler : callable
-
the event handler
- $data : mixed = null
-
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 [[Event::data]].
- $append : bool = true
-
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.
Tags
set()
Registers a component definition with this locator.
public
set(string $id, mixed $definition) : mixed
For example,
// a class name
$locator->set('cache', 'yii\caching\FileCache');
// a configuration array
$locator->set('db', [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
]);
// an anonymous function
$locator->set('cache', function ($params) {
return new \yii\caching\FileCache;
});
// an instance
$locator->set('cache', new \yii\caching\FileCache);
If a component definition with the same ID already exists, it will be overwritten.
Parameters
- $id : string
-
component ID (e.g.
db
). - $definition : mixed
-
the component definition to be registered with this locator. It can be one of the following:
- a class name
- 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 is required and stands for the the class of the object to be created. - a PHP callable: either an anonymous function or an array representing a class method (e.g.
['Foo', 'bar']
). The callable will be called by [[get()]] to return an object associated with the specified component ID. - an object: When [[get()]] is called, this object will be returned.
Tags
setComponents()
Registers a set of component definitions in this locator.
public
setComponents(array<string|int, mixed> $components) : mixed
This is the bulk version of [[set()]]. The parameter should be an array whose keys are component IDs and values the corresponding component definitions.
For more details on how to specify component IDs and definitions, please refer to [[set()]].
If a component definition with the same ID already exists, it will be overwritten.
The following is an example for registering two component definitions:
[
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'sqlite:path/to/file.db',
],
'cache' => [
'class' => 'yii\caching\DbCache',
'db' => 'db',
],
]
Parameters
- $components : array<string|int, mixed>
-
component definitions or instances
trigger()
Triggers an event.
public
trigger(string $name[, Event|null $event = null ]) : mixed
This method represents the happening of an event. It invokes all attached handlers for the event including class-level handlers.
Parameters
- $name : string
-
the event name
- $event : Event|null = null
-
the event instance. If not set, a default [[Event]] object will be created.
attachBehaviorInternal()
Attaches a behavior to this component.
private
attachBehaviorInternal(string|int $name, string|array<string|int, mixed>|Behavior $behavior) : Behavior
Parameters
- $name : string|int
-
the name of the behavior. If this is an integer, it means the behavior is an anonymous one. Otherwise, the behavior is a named one and any existing behavior with the same name will be detached first.
- $behavior : string|array<string|int, mixed>|Behavior
-
the behavior to be attached
Return values
Behavior —the attached behavior.