N
N
nepster-web2015-02-18 03:56:18
Yii
nepster-web, 2015-02-18 03:56:18

How and when to use DI in Yii2?

Many scold yii for being static and highly connected, on small projects this is not very scary, but sometimes it goes sideways.
The question is how to use DI in yii2 correctly, namely, I want to understand and consider a classic example when you need to access the model of another module from 1 module.
There are docs:
https://github.com/yiisoft/yii2/blob/master/docs/g...
Everything is great, but I have not worked with this thing before and it is not clear where and when to transfer dependencies.
Well, for example, there is an article module, articles are written by users, when adding an article, I need to play tricks with the author, that is, get the user module in the article model.
Now I directly connect the user model and work with it in the article model. These are 2 different modules and there is a feeling of discomfort.
Please explain (very preferably with code examples) how to use DI in yii2 in such cases (where to inject dependencies)?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Makarov, 2015-02-18
@nepster-web

DI has nothing to do with your case. It is a way of implementation, not the idea itself. The idea is that you need to implement the dependency inversion principle. That is, start working with interfaces, and not with concrete implementations.
To be generic and portable, a module must not be aware of models from outside of itself. Instead, it must express its requirements as an interface, and external models must implement this interface.
For your example, we make interfaces in the Article module:

interface ArticleInterface
{
    public function getTitle();
    public function getAuthor();
}

interface ArticleAuthorInterface
{
    public function getName();
    public function getID();
}

Further, within the module, we use only interfaces, and not the models themselves:
public function renderArticle(ArticleInterface $article)
{
    return $this->renderPartial('_article', [
         'author' => $article->getAuthor(), 
         'title' => $article->getTitle()
    ]);
}

Outside of the module, we will have to implement the interfaces in the models:
class Article extends ActiveRecord implements ArticleInterface
{
   // ...
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question