Skip to content
PHP Ecosystem
Explore

ServiceLocator

API reference › yii › di › ServiceLocator

classyii\di\ServiceLocator
Extendsyii\base\Component » yii\base\BaseObject
Implementsyii\base\Configurable
Since2.0
Sourceframework/di/ServiceLocator.php
1 subclass

ServiceLocator implements a service locator.

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

PropertyTypeDescriptionDefined by
$behaviors read-onlyarray<yii\base\Behavior<static>>List of behaviors attached to this component.yii\base\Component
$componentsarrayThe list of the component definitions or the loaded component instances (ID => definition or instance).ServiceLocator
MethodDescriptionDefined by
__construct()Constructor.yii\base\BaseObject
__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
__get()Getter magic method.ServiceLocator
__isset()Checks if a property value is null.ServiceLocator
__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() staticReturns the fully qualified name of this class.yii\base\BaseObject
clear()Removes the component from the locator.ServiceLocator
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 the component instance with the specified ID.ServiceLocator
getBehavior()Returns the named behavior object.yii\base\Component
getBehaviors()Returns all behaviors attached to this component.yii\base\Component
getComponents()Returns the list of the component definitions or the loaded component instances.ServiceLocator
has()Returns a value indicating whether the locator has the specified component definition or has instantiated the component.ServiceLocator
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
init()Initializes the object.yii\base\BaseObject
off()Detaches an existing event handler from this component.yii\base\Component
on()Attaches an event handler to an event.yii\base\Component
set()Registers a component definition with this locator.ServiceLocator
setComponents()Registers a set of component definitions in this locator.ServiceLocator
trigger()Triggers an event.yii\base\Component
public function __get(string $name): mixed

Getter magic method.

This method is overridden to support accessing components like reading properties.

Parameters

ParameterTypeDescription
$namestringComponent or property name

Returns

mixed: The named property value

public function __isset(string $name): bool

Checks if a property value is null.

This method overrides the parent implementation by checking if the named component is loaded.

Parameters

ParameterTypeDescription
$namestringThe property name or the event name

Returns

bool: Whether the property value is null

public function clear(string $id): mixed

Removes the component from the locator.

Parameters

ParameterTypeDescription
$idstringThe component ID

Returns

mixed

public function get(string $id, bool $throwException = true): ($throwException is true ? object : object|null)

Returns the component instance with the specified ID.

Parameters

ParameterTypeDescription
$idstringComponent ID (e.g. db).
$throwExceptionboolWhether to throw an exception if $id is not registered with the locator before.

Returns

($throwException is true ? object : object|null): The component of the specified ID. If $throwException is false and $id is not registered before, null will be returned.

Throws

See also

public function getComponents(bool $returnDefinitions = true): array

Returns the list of the component definitions or the loaded component instances.

Parameters

ParameterTypeDescription
$returnDefinitionsboolWhether to return component definitions instead of the loaded component instances.

Returns

array: The list of the component definitions or the loaded component instances (ID => definition or instance).

public function has(string $id, bool $checkInstance = false): bool

Returns a value indicating whether the locator has the specified component definition or has instantiated the component.

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

ParameterTypeDescription
$idstringComponent ID (e.g. db).
$checkInstanceboolWhether the method should check if the component is shared and instantiated.

Returns

bool: Whether the locator has the specified component definition or has instantiated the component.

See also

public function set(string $id, mixed $definition): mixed

Registers a component definition with this locator.

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

ParameterTypeDescription
$idstringComponent ID (e.g. db).
$definitionmixedThe 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.

Returns

mixed

Throws

public function setComponents(array $components): mixed

Registers a set of component definitions in this locator.

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

ParameterTypeDescription
$componentsarrayComponent definitions or instances

Returns

mixed