For example,
php
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 Container::has to check if a class definition already exists.
public set ( string $class, mixed $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. |
public function testDefault() { $namespace = __NAMESPACE__ . '\\stubs'; $QuxInterface = "{$namespace}\\QuxInterface"; $Foo = Foo::className(); $Bar = Bar::className(); $Qux = Qux::className(); // automatic wiring $container = new Container(); $container->set($QuxInterface, $Qux); $foo = $container->get($Foo); $this->assertTrue($foo instanceof $Foo); $this->assertTrue($foo->bar instanceof $Bar); $this->assertTrue($foo->bar->qux instanceof $Qux); // full wiring $container = new Container(); $container->set($QuxInterface, $Qux); $container->set($Bar); $container->set($Qux); $container->set($Foo); $foo = $container->get($Foo); $this->assertTrue($foo instanceof $Foo); $this->assertTrue($foo->bar instanceof $Bar); $this->assertTrue($foo->bar->qux instanceof $Qux); // wiring by closure $container = new Container(); $container->set('foo', function () { $qux = new Qux(); $bar = new Bar($qux); return new Foo($bar); }); $foo = $container->get('foo'); $this->assertTrue($foo instanceof $Foo); $this->assertTrue($foo->bar instanceof $Bar); $this->assertTrue($foo->bar->qux instanceof $Qux); // wiring by closure which uses container $container = new Container(); $container->set($QuxInterface, $Qux); $container->set('foo', function (Container $c, $params, $config) { return $c->get(Foo::className()); }); $foo = $container->get('foo'); $this->assertTrue($foo instanceof $Foo); $this->assertTrue($foo->bar instanceof $Bar); $this->assertTrue($foo->bar->qux instanceof $Qux); // predefined constructor parameters $container = new Container(); $container->set('foo', $Foo, [Instance::of('bar')]); $container->set('bar', $Bar, [Instance::of('qux')]); $container->set('qux', $Qux); $foo = $container->get('foo'); $this->assertTrue($foo instanceof $Foo); $this->assertTrue($foo->bar instanceof $Bar); $this->assertTrue($foo->bar->qux instanceof $Qux); }
/** * Generate fake data and */ public function actionGenerate() { $input = $this->parseArguments(func_get_args()); $container = new Container(); $container->set(GeneratorInterface::class, array_merge(['class' => $this->generator_fqn], $input['generator'])); $container->set(DbProviderInterface::class, array_merge(['class' => $this->dbprovider_fqn], $input['dbprovider'])); $this->generator_obj = $container->get(GeneratorInterface::class); if (!$this->force && !$this->confirmGeneration()) { return; } $this->dbprovider_obj = $container->get(DbProviderInterface::class); Console::startProgress(0, $this->count); foreach ($this->dbprovider_obj->export($this->count) as $count) { Console::updateProgress($this->count - $count, $this->count); } Console::endProgress(true); }
public function testEnsure() { $container = new Container(); $container->set('db', ['class' => 'yii\\db\\Connection', 'dsn' => 'test']); $this->assertTrue(Instance::ensure('db', 'yii\\db\\Connection', $container) instanceof Connection); $this->assertTrue(Instance::ensure(new Connection(), 'yii\\db\\Connection', $container) instanceof Connection); $this->assertTrue(Instance::ensure(['class' => 'yii\\db\\Connection', 'dsn' => 'test'], 'yii\\db\\Connection', $container) instanceof Connection); }
/** * @return Container */ private static function getIoc() { $diConfig = (include 'di.php'); $container = new Container(); $container->setSingleton('workerMapper', $diConfig['workerMapper']); $container->setSingleton('entityfx\\utils\\workers\\contracts\\repositories\\WorkerRepositoryInterface', function ($container, $params, $config) use($diConfig) { return $container->get($diConfig['workerRepository'], [$container->get('workerMapper')]); }); $container->set('entityfx\\utils\\workers\\contracts\\WorkerInterceptorInterface', function ($container, $params, $config) use($diConfig) { return $container->get($diConfig['workerInterceptor'], [$params['worker'], $container->get('entityfx\\utils\\workers\\contracts\\repositories\\WorkerRepositoryInterface')]); }); return $container; }
public function init() { $diConfig = (include 'di.php'); $container = new Container(); $container->setSingleton('ObjectHistoryMapper', $diConfig['mapper']); $container->setSingleton('entityfx\\utils\\objectHistory\\contracts\\repositories\\ObjectHistoryRepositoryInterface', function ($container, $params, $config) use($diConfig) { return $container->get($diConfig['repository'], [$container->get('ObjectHistoryMapper')]); }); $container->set('entityfx\\utils\\objectHistory\\contracts\\ObjectHistoryManagerInterface', function ($container, $params, $config) use($diConfig) { return $container->get($diConfig['manager'], [$container->get('entityfx\\utils\\objectHistory\\contracts\\repositories\\ObjectHistoryRepositoryInterface')]); }); $this->initEventHandlers($container); parent::init(); }
/** * 待改进 未测试 * @param \yii\di\Container $container * @param array $serviceConfig */ public function configureContainer($container, $serviceConfig) { foreach ($serviceConfig as $class => $definition) { $container->set($class, $definition); } }
public function registerDependencies() { $this->conteiner->set('bl\\locale\\provider\\LanguageProviderInterface', $this->languageProvider); $this->conteiner->set('languageProvider', 'bl\\locale\\provider\\LanguageProviderInterface'); }