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
?
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.
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.
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.
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.
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'
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With