samdark / yii2-cookbook

Yii 2.0 Community Cookbook

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Are there some best practices of handling relations in advanced template?

antonmarin opened this issue · comments

There are models:

  • common\models\commonModel
  • common\models\commonRelatedModel
  • frontend\models\frontModel

frontModel extends commonModel
commonModel has some relation: commonModel->getRelatedModel()
so to get commonRelatedModel from frontModel i just ask frontModel()->getRelatedModel()

but if i add frontend\models\frontRelatedModel, then to get frontRelatedModel i have to override getRelatedModel()

Is it right or there is another way?

The best thing to do in this case is not to mix these models. It's often called bounded contexts. The idea is that contexts are different so it's best to avoid reusing model even if the name is the same and functionality is close.

class MainModel extends ActiveRecord
{
    protected function getRelationName($class)
    {
        $myClass = get_called_class();
        $myNS = substr($myClass, 0, strrpos($myClass, '\\'));

        return $myNS . substr($class, strrpos($class, '\\'));
    }
}
class commonModel extends MainModel
{
    public function getRelatedModel()
    {
        return $this->hasOne(static::getRelationName(RelatedModel::className()), [...]);
    }
}

@thiagotalma technically it's possible but I'd not recommend it.

I'll leave this open since it could be made into recipe.