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

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

报告相同问题?

悬赏问题

  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥15 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)