Dependency Injection in models

Let’s assume we have Post active record for example and we want to have a relation from Post to some owner. And let’s assume we are trying to implement generic extension, which can be used in different projects, so we don’t really know what is the real class of owner. One of the solutions could be having special field indicating which owner model class to use.


class Post extends \yii\db\ActiveRecord

{

    /**

     * @var string

     */

    public $ownerModelClass;


    /**

     * @return \yii\db\ActiveQuery

     */

    public function getOwner()

    {

        return $this->hasOne($this->ownerModelClass, ['id' => 'owner_id']);

    }

}

But in this case we’ll have to set $post->ownerModelClass field each time we want to get owner, and joining it will not be possible at all.

So I’m wondering why there is no base level DI support for models, like we have it in Widgets for example.

Let’s assume we introduce the following static method in \yii\base\Model class:


    /**

     * @return Model

     */

    public static function create()

    {

        return \Yii::createObject(get_called_class());

    }

And change all methods in Yii core to use static::create instead of new operator. I.e. for ActiveRecord:


    /**

     * @return object

     */

    public static function instantiate($row)

    {

        return static::create();

    }

With such an approach we’ll be able to Inject dependencies in models easily when configuring application.

Am I missing something? may be it’s not really necessary or there is another approach to achieve desired result for my situation?