In the pursuit to automate all my "dependency injection", I use construct() and instantiate(). This way:
class Whatever extends ActiveRecord
{
...
public function __construct(Translator $translator, User $user, Tenant $tenant, array $config = [])
{
$this->translator = $translator;
$this->user = $user;
$this->language = $user->getIdentity()->language;
$this->tenant = $tenant;
parent::__construct($config);
}
public static function instantiate($row)
{
return \Yii::createObject( self::className() );
}
But I MUST use either any find…() method or \Yii::createObject() to interact with my model or I get a
[color="#FF0000"]
"Argument 1 passed to common\\models\\Whatever::__construct() must be an instance of common\\components\\Translator, none given, called in /var/www/html/gtbcloud/vendor/yiisoft/yii2/db/BaseActiveRecord.php on line 1163"[/color]
But strangely Yii2 use "new" everywhere to create models.
Ex:
yii\data\ActiveDataProvider
...
public function setSort($value)
{
parent::setSort($value);
if (($sort = $this->getSort()) !== false && $this->query instanceof ActiveQueryInterface) {
/* @var $model Model */
$model = new $this->query->modelClass; //<--- here
...
It makes me rethink my entire approach. Why Yii2 use “new” everywhere while pushing their “Dependency Injection Container” feature that is not compatible with “new”? I can’t even use a basic feature like “ActiveDataProvider”.
[size="5"][color="#0000FF"]
How can I setup my model to use DI and still be compatible with "new"??
Is there something I’m missing? …I just don’t get it [/color][/size]