di\ServiceLocator set()

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

doc_Yii
2016-10-30 17:01:10
Comments
Leave a Comment

Please login to continue.