To use ServiceLocator, you first need to register component IDs with the corresponding component
definitions with the locator by calling ServiceLocator::set or ServiceLocator::setComponents.
You can then call ServiceLocator::get to retrieve a component with the specified ID. The locator will automatically
instantiate and configure the component according to the definition.
For example,
php
$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.
For more details and usage information on ServiceLocator, see the guide article on service locators.