# ServiceLocator

> ServiceLocator implements a [service locator](https://en.wikipedia.org/wiki/Service_locator_pattern).

[API reference](/docs/api/index.md) › [yii](/docs/api/yii/index.md) › [di](/docs/api/yii/di/index.md) › ServiceLocator

| class | `yii\di\ServiceLocator` |
| --- | --- |
| Extends | [`yii\base\Component`](/docs/api/yii/base/component/index.md) » [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| Implements | [`yii\base\Configurable`](/docs/api/yii/base/configurable/index.md) |
| Since | 2.0 |
| Source | [`framework/di/ServiceLocator.php`](https://github.com/yiisoft/yii2/blob/22.0/framework/di/ServiceLocator.php#L54) |

1 subclass:

- [`yii\base\Module`](/docs/api/yii/base/module/index.md)

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()`](/docs/api/yii/di/servicelocator/index.md#method-set) or [`setComponents()`](/docs/api/yii/di/servicelocator/index.md#method-setComponents).
You can then call [`get()`](/docs/api/yii/di/servicelocator/index.md#method-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`](/docs/api/yii/base/module/index.md) extends from ServiceLocator, modules and the application are all service locators.
Modules add [tree traversal](/docs/guide/concept-service-locator/index.md#tree-traversal) for service resolution.

For more details and usage information on ServiceLocator, see the [guide article on service locators](/docs/guide/concept-service-locator/index.md).

## Properties

| Property | Type | Description | Defined by |
| --- | --- | --- | --- |
| <span id="property-behaviors"></span>[`$behaviors`](/docs/api/yii/base/component/index.md#property-behaviors) read-only | `array<`[`yii\base\Behavior`](/docs/api/yii/base/behavior/index.md)`<static>>` | List of behaviors attached to this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="property-components"></span>`$components` | `array` | The list of the component definitions or the loaded component instances (ID => definition or instance). | `ServiceLocator` |

## Methods

| Method | Description | Defined by |
| --- | --- | --- |
| <span id="method-__construct"></span>[`__construct()`](/docs/api/yii/base/baseobject/index.md#method-__construct) | Constructor. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-__call"></span>[`__call()`](/docs/api/yii/base/component/index.md#method-__call) | Calls the named method which is not a class method. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__clone"></span>[`__clone()`](/docs/api/yii/base/component/index.md#method-__clone) | This method is called after the object is created by cloning an existing one. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`__get()`](#method-__get) | Getter magic method. | `ServiceLocator` |
| [`__isset()`](#method-__isset) | Checks if a property value is null. | `ServiceLocator` |
| <span id="method-__set"></span>[`__set()`](/docs/api/yii/base/component/index.md#method-__set) | Sets the value of a component property. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__unset"></span>[`__unset()`](/docs/api/yii/base/component/index.md#method-__unset) | Sets a component property to be null. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-attachBehavior"></span>[`attachBehavior()`](/docs/api/yii/base/component/index.md#method-attachBehavior) | Attaches a behavior to this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-attachBehaviors"></span>[`attachBehaviors()`](/docs/api/yii/base/component/index.md#method-attachBehaviors) | Attaches a list of behaviors to the component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-behaviors"></span>[`behaviors()`](/docs/api/yii/base/component/index.md#method-behaviors) | Returns a list of behaviors that this component should behave as. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-canGetProperty"></span>[`canGetProperty()`](/docs/api/yii/base/component/index.md#method-canGetProperty) | Returns a value indicating whether a property can be read. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-canSetProperty"></span>[`canSetProperty()`](/docs/api/yii/base/component/index.md#method-canSetProperty) | Returns a value indicating whether a property can be set. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-className"></span>[`className()`](/docs/api/yii/base/baseobject/index.md#method-className) static | Returns the fully qualified name of this class. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| [`clear()`](#method-clear) | Removes the component from the locator. | `ServiceLocator` |
| <span id="method-detachBehavior"></span>[`detachBehavior()`](/docs/api/yii/base/component/index.md#method-detachBehavior) | Detaches a behavior from the component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-detachBehaviors"></span>[`detachBehaviors()`](/docs/api/yii/base/component/index.md#method-detachBehaviors) | Detaches all behaviors from the component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-ensureBehaviors"></span>[`ensureBehaviors()`](/docs/api/yii/base/component/index.md#method-ensureBehaviors) | Makes sure that the behaviors declared in [`behaviors()`](/docs/api/yii/base/component/index.md#method-behaviors) are attached to this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`get()`](#method-get) | Returns the component instance with the specified ID. | `ServiceLocator` |
| <span id="method-getBehavior"></span>[`getBehavior()`](/docs/api/yii/base/component/index.md#method-getBehavior) | Returns the named behavior object. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-getBehaviors"></span>[`getBehaviors()`](/docs/api/yii/base/component/index.md#method-getBehaviors) | Returns all behaviors attached to this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`getComponents()`](#method-getComponents) | Returns the list of the component definitions or the loaded component instances. | `ServiceLocator` |
| [`has()`](#method-has) | Returns a value indicating whether the locator has the specified component definition or has instantiated the component. | `ServiceLocator` |
| <span id="method-hasEventHandlers"></span>[`hasEventHandlers()`](/docs/api/yii/base/component/index.md#method-hasEventHandlers) | Returns a value indicating whether there is any handler attached to the named event. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-hasMethod"></span>[`hasMethod()`](/docs/api/yii/base/component/index.md#method-hasMethod) | Returns a value indicating whether a method is defined. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-hasProperty"></span>[`hasProperty()`](/docs/api/yii/base/component/index.md#method-hasProperty) | Returns a value indicating whether a property is defined for this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-init"></span>[`init()`](/docs/api/yii/base/baseobject/index.md#method-init) | Initializes the object. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-off"></span>[`off()`](/docs/api/yii/base/component/index.md#method-off) | Detaches an existing event handler from this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-on"></span>[`on()`](/docs/api/yii/base/component/index.md#method-on) | Attaches an event handler to an event. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`set()`](#method-set) | Registers a component definition with this locator. | `ServiceLocator` |
| [`setComponents()`](#method-setComponents) | Registers a set of component definitions in this locator. | `ServiceLocator` |
| <span id="method-trigger"></span>[`trigger()`](/docs/api/yii/base/component/index.md#method-trigger) | Triggers an event. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |

## Method details

### __get() <span id="method-__get"></span>

```php
public function __get(string $name): mixed
```

Getter magic method.

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

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$name` | `string` | Component or property name |

**Returns**

`mixed`: The named property value

### __isset() <span id="method-__isset"></span>

```php
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**

| Parameter | Type | Description |
| --- | --- | --- |
| `$name` | `string` | The property name or the event name |

**Returns**

`bool`: Whether the property value is null

### clear() <span id="method-clear"></span>

```php
public function clear(string $id): mixed
```

Removes the component from the locator.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$id` | `string` | The component ID |

**Returns**

`mixed`

### get() <span id="method-get"></span>

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

Returns the component instance with the specified ID.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$id` | `string` | Component ID (e.g. `db`). |
| `$throwException` | `bool` | Whether 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**

- [`yii\base\InvalidConfigException`](/docs/api/yii/base/invalidconfigexception/index.md): if `$id` refers to a nonexistent component ID

**See also**

- [`has()`](/docs/api/yii/di/servicelocator/index.md#method-has)
- [`set()`](/docs/api/yii/di/servicelocator/index.md#method-set)

### getComponents() <span id="method-getComponents"></span>

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

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

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$returnDefinitions` | `bool` | Whether 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).

### has() <span id="method-has"></span>

```php
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**

| Parameter | Type | Description |
| --- | --- | --- |
| `$id` | `string` | Component ID (e.g. `db`). |
| `$checkInstance` | `bool` | Whether 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**

- [`set()`](/docs/api/yii/di/servicelocator/index.md#method-set)

### set() <span id="method-set"></span>

```php
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**

| Parameter | Type | Description |
| --- | --- | --- |
| `$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()`](/docs/api/yii/di/servicelocator/index.md#method-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()`](/docs/api/yii/di/servicelocator/index.md#method-get) to return an object associated with the specified component ID. - an object: When [`get()`](/docs/api/yii/di/servicelocator/index.md#method-get) is called, this object will be returned. |

**Returns**

`mixed`

**Throws**

- [`yii\base\InvalidConfigException`](/docs/api/yii/base/invalidconfigexception/index.md): if the definition is an invalid configuration array

### setComponents() <span id="method-setComponents"></span>

```php
public function setComponents(array $components): mixed
```

Registers a set of component definitions in this locator.

This is the bulk version of [`set()`](/docs/api/yii/di/servicelocator/index.md#method-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()`](/docs/api/yii/di/servicelocator/index.md#method-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**

| Parameter | Type | Description |
| --- | --- | --- |
| `$components` | `array` | Component definitions or instances |

**Returns**

`mixed`