Where should I setup DI container in Yii2?

Viewed 1180

I have an interface. And a class. The classimplements the interface and extends BaseObject. It's something like business logic service. I a'm going to inject it in a controlller via constructor. My target is use dependency from the interface.

I'm looking on the documentation and I don't understand, where should I write this code. Is it a parth of main config? Or it's some kind of new one config? Is it a separete file? If yse, how Yii2 will understand that it's DI configuration?

1 Answers

You can set up DI container in your app config. For example in web.php config:

$config = [
    // ... 
    'container' => [
        'definitions' => [
            \my\namespace\MyInterface::class => \my\namespace\MyClass::class,
            // ... other definitions
        ],
    ],
    // ... other configs
];

Another good place to set up DI might be in bootstrap method of component. For example in Module class.

class MyModule extends \yii\base\Module implements \yii\base\BootstrapInterface
{
    public function bootstrap($app)
    {
        Yii::$container->set(
            \my\namespace\MyInterface::class,
            \my\namespace\MyClass::class
        );
    }
}

In this case you have to add the module to app's bootstrap property.

Related