dtukyb8095 2016-11-28 17:20
浏览 22
已采纳

PHP Laravel Parents从子级继承动态静态参数

I am working with Laravel Eloquent models and have gotten stuck on an inheritence issue.

I have got BaseModel class, which has protected static $dynamicRelations = []; parameter, and some methods to work with that.

And then I have multiple other classes, extending BaseModel, for this example let's say PageModel and EventModel.

If I create a dynamic relation on the page model, as such PageModel::setDynamicRelation, it puts it in the static variable:

    public static function setDynamicRelation($key, $callback)
    {
        static::$dynamicRelations[$key] = $callback;
    }

This way, I can add a dynamic relationship to the model. So if I do PageModel::setDynamicRelation('banners', ...), then on an instance of PageModel I can call PageModel->banners to retrieve the relationship values.

The issue is, that the relations are kept in the BaseModel static parameter, and are inherited by other models. So if I set the relationsip on PageModel, and then instantiate an EventModel, it also gets those same relationships, which is not correct.

How can I make it so that the relationships are stored in the child class and are not inherited by other classes? I.e. need to store a copy of $dynamicRelations on the class that the methods are called upon, so all the children don't share same relations?

Thanks!

  • 写回答

1条回答 默认 最新

  • dongpo2458 2016-11-28 19:33
    关注

    Do you have tests showing this?

    So you are stating that you do not want Late Static Bindings

    Static properties on parent classes that are defined in child classes don't propagate to other child instances that extend the parent model. For example, Illuminate\Database\Eloquent\Model has the protected static $globalScopes = []; property but when you add a global scope to any model extending Model it pushes it in this array just as you are doing with your $dynamicRelationships array but those instances do not get reflected in the classes extending Model.

    See Laravel's implementation of this here

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?