M
M
Maybe_V2017-01-22 01:59:21
Yii
Maybe_V, 2017-01-22 01:59:21

How to properly inject Yii2 class dependencies?

Help me understand where I'm wrong. It seems like I'm doing everything right!
We need to extend the functionality of the class:

use custom\class\Finder;
class BaseLoginForm extends Model
{
    /** @var Finder */
    protected $finder;

    /**
     * @param Finder $finder
     * @param array  $config
     */
    public function __construct(Finder $finder, $config = [])
    {
        $this->finder = $finder;
        parent::__construct($config);
    }
}

I do like this:
use own\class\Finder;
class LoginForm extends BaseLoginForm
{
    /** @var Finder */
    protected $finder;

    /**
     * @param Finder $finder
     * @param array  $config
     */
    public function __construct(Finder $finder, $config = [])
    {
        $this->finder = $finder;
        parent::__construct($finder, $config);
        
    }
}

The problem is that after I do this - $finder = null !
Perhaps Finderthe class needs to be registered somewhere so that it Yiiknows where to inject the dependency ????? Help me to understand !

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ilya, 2017-01-22
@rpsv

In the child class, it is not necessary to describe finderthe constructor either, because they are inherited.
Concerning implementation: whence Yii2 should take a class Finder?
And in fact, the following code is also an injection:

$finder = new Finder();
$loginForm = new LoginForm($finder);

Or do you not like this option?

M
Maxim Fedorov, 2017-01-23
@qonand

Use the built-in dependency container

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question