Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I inject interface into controller's constructor in Yii2

I would like to inject interface app\models\IFoo

private $foo;

public function __construct($id, $module, IFoo $foo, array $config = [])
{
    parent::__construct($id, $module, $config);
    $this->foo = $foo;
}

How should I set container to correct resolving the dependency in concrete class app\models\Foo which implements IFoo?

like image 839
GraDea Avatar asked Jan 02 '17 08:01

GraDea


People also ask

Can we inject dependency in interface?

interface injection: the dependency provides an injector method that will inject the dependency into any client passed to it. Clients must implement an interface that exposes a setter method that accepts the dependency.

How do you inject dependencies?

The injector class injects dependencies broadly in three ways: through a constructor, through a property, or through a method. Constructor Injection: In the constructor injection, the injector supplies the service (dependency) through the client class constructor.

What is dependency injection container?

A DI Container is a framework to create dependencies and inject them automatically when required. It automatically creates objects based on the request and injects them when required. DI Container helps us to manage dependencies within the application in a simple and easy way.

What is controller in Yii?

Controllers are part of the MVC architecture. They are objects of classes extending from yii\base\Controller and are responsible for processing requests and generating responses.


1 Answers

Try to call it like that in entry script:

\Yii::$container->set('app\models\IFoo', $concreteClass);

where $concreteClass is either 'app\models\Foo' or 'app\models\FooStub'.

like image 136
Bizley Avatar answered Oct 02 '22 00:10

Bizley