Answer the question
In order to leave comments, you need to log in
Is the approach to implementing DI in Yii2 projects correct or not?
Hello.
UPD: I'll just leave it here
stackoverflow.com/questions/24381708/default-value...
In my Yii2 projects, I use the following construction quite actively:
use app\models\Dependency;
class Model extends yii\base\Model
{
public $dependencyClass;
public function __construct($config = [])
{
if (!isset($config['dependencyClass'])) {
$this->dependencyClass = new Dependency();
}
parent::__construct($config);
}
}
public function getDependencies()
{
return $this->hasMany($this->dependencyClass->className(), ['modelId' => 'id']);
}
Answer the question
In order to leave comments, you need to log in
Some one-sided solution:
if (!isset($config['dependencyClass'])) {
$this->dependencyClass = new Dependency();
}
//config/web.php
"components"=>[
//...
"model_deps"=>[
"class"=>"app\components\ModelDependenciesService",
"default_dependency"=>"app\model\model_2",
"dependencies"=>[
"app\model\model_1"=>[
"dep_1"=>"app\model\model_3",
//....
]
]
]
//...
]
// в базовом классе модели
public function getDepClass($dep_name){
retrn Yii::$app->model_deps->depClass(static,$dep_name); // не помню точно как текущий класс брать
}
// где-то в модели
public function getDependencies()
{
return $this->hasMany($this->getDepClass($dep_name), ['modelId' => 'id']);
}
What's wrong with the classic version?
Declare the interface that the dependent model needs and directly into its constructor, you can inherit from ActiveRecordInterface
Let your model be Post with Dependency Comments
interface PostCommentModelInterface // можно extends ActiveRecordInterface
{
/**
* @return ActiveRecord[]|Comment[]
**/
public function findForPost();
}
class Model extends yii\base\Model
{
protected $commentModel;
public function __construct(PostCommentModelInterface $commentModel, $config = [])
{
$this->commentModel = $commentModel;
parent::__construct($config);
}
]
...
protected $commentModel;
public function __construct(\yii\container\Container $container, $config = [])
{
$this->commentModel = $container->get('\app\modules\posts\PostCommentModelInterface'');
parent::__construct($config);
}
...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question