# Class yii\di\ServiceLocator

Inheritance | yii\di\ServiceLocator » yii\base\Component » yii\base\BaseObject
Implements | yii\base\Configurable
Subclasses | yii\base\Application, yii\base\Module, yii\console\Application, yii\debug\Module, yii\gii\Module, yii\web\Application
Available since version | 2.0
Source Code | https://github.com/yiisoft/yii2/blob/master/framework/di/ServiceLocator.php

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

## Public Properties

Hide inherited 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
$components | array | The list of the component definitions or the loaded component instances (ID => definition or instance). | yii\di\ServiceLocator

## Public Methods

Hide inherited 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() | Getter magic method. | yii\di\ServiceLocator
__isset() | Checks if a property value is null. | yii\di\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() | Returns the fully qualified name of this class. | yii\base\BaseObject
clear() | Removes the component from the locator. | yii\di\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. | yii\di\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. | yii\di\ServiceLocator
has() | Returns a value indicating whether the locator has the specified component definition or has instantiated the component. | yii\di\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. | yii\di\ServiceLocator
setComponents() | Registers a set of component definitions in this locator. | yii\di\ServiceLocator
trigger() | Triggers an event. | yii\base\Component

## Property Details

$components public property

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

public array $components = null

## Method Details

__get() public method

Getter magic method.

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

public mixed __get ( $name )
$name | string | Component or property name
return | mixed | The named property value

__isset() public method

Checks if a property value is null.

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

public boolean __isset ( $name )
$name | string | The property name or the event name
return | boolean | Whether the property value is null

clear() public method

Removes the component from the locator.

public void clear ( $id )
$id | string | The component ID

get() public method

Returns the component instance with the specified ID.

See also:

- has()
- set()

public object|null get ( $id, $throwException = true )
$id | string | Component ID (e.g. `db`).
$throwException | boolean | Whether to throw an exception if `$id` is not registered with the locator before.
return | object|null | The component of the specified ID. If `$throwException` is false and `$id` is not registered before, null will be returned.
throws | yii\base\InvalidConfigException | if `$id` refers to a nonexistent component ID

getComponents() public method

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

public array getComponents ( $returnDefinitions = true )
$returnDefinitions | boolean | Whether to return component definitions instead of the loaded component instances.
return | array | The list of the component definitions or the loaded component instances (ID => definition or instance).

has() public method

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.

See also set().

public boolean has ( $id, $checkInstance = false )
$id | string | Component ID (e.g. `db`).
$checkInstance | boolean | Whether the method should check if the component is shared and instantiated.
return | boolean | Whether the locator has the specified component definition or has instantiated the component.

set() public method

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.

public void set ( $id, $definition )
$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.
throws | yii\base\InvalidConfigException | if the definition is an invalid configuration array

setComponents() public method

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',
        ],
    ]

public void setComponents ( $components )
$components | array | Component definitions or instances