samdark / yii2-cookbook

Yii 2.0 Community Cookbook
1.45k stars 297 forks source link

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

Open antonmarin opened 7 years ago

antonmarin commented 7 years ago

There are models:

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?

samdark commented 7 years ago

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.

thiagotalma commented 7 years ago
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()), [...]);
    }
}
samdark commented 7 years ago

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

antonmarin commented 7 years ago

tnx

samdark commented 7 years ago

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