di\Container set()

set() public method

Registers a class definition with this container.

For example,

// register a class name as is. This can be skipped.
$container->set('yii\db\Connection');

// register an interface
// When a class depends on the interface, the corresponding class
// will be instantiated as the dependent object
$container->set('yii\mail\MailInterface', 'yii\swiftmailer\Mailer');

// register an alias name. You can use $container->get('foo')
// to create an instance of Connection
$container->set('foo', 'yii\db\Connection');

// register a class with configuration. The configuration
// will be applied when the class is instantiated by get()
$container->set('yii\db\Connection', [
    'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
    'username' => 'root',
    'password' => '',
    'charset' => 'utf8',
]);

// register an alias name with class configuration
// In this case, a "class" element is required to specify the class
$container->set('db', [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
    'username' => 'root',
    'password' => '',
    'charset' => 'utf8',
]);

// register a PHP callable
// The callable will be executed when $container->get('db') is called
$container->set('db', function ($container, $params, $config) {
    return new \yii\db\Connection($config);
});

If a class definition with the same name already exists, it will be overwritten with the new one. You may use has() to check if a class definition already exists.

public $this set ( $class, $definition = [], array $params = [] )
$class string

Class name, interface name or alias name

$definition mixed

The definition associated with $class. It can be one of the following:

  • a PHP callable: The callable will be executed when get() is invoked. The signature of the callable should be function ($container, $params, $config), where $params stands for the list of constructor parameters, $config the object configuration, and $container the container object. The return value of the callable will be returned by get() as the object instance requested.
  • 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 stands for the the class of the object to be created. If class is not specified, $class will be used as the class name.
  • a string: a class name, an interface name or an alias name.
$params array

The list of constructor parameters. The parameters will be passed to the class constructor when get() is called.

return $this

The container itself

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

Please login to continue.