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!

图片转代码服务由CSDN问答提供 功能建议

我正在使用Laravel Eloquent模型并且遇到了继承问题。

我有 BaseModel 类,它有 protected static $ dynamicRelations = []; 参数,以及一些使用它的方法。 \ n

然后我有多个其他类,扩展 BaseModel ,对于这个例子,让我们说 PageModel EventModel \ n

如果我在页面模型上创建动态关系,如 PageModel :: setDynamicRelation ,则将其置于静态变量中:

   public static function setDynamicRelation($ key,$ callback)
 {
 static :: $ dynamicRelations [$ key] = $ callback; 
} 
   
 
 <  p>这样,我可以为模型添加动态关系。 因此,如果我执行 PageModel :: setDynamicRelation('banners',...),那么在 PageModel 的实例上,我可以调用 PageModel-&gt; banners <  / code>来检索关系值。 
 
 

问题是,关系保存在 BaseModel 静态参数中,并由其他模型继承。 因此,如果我在 PageModel 上设置了relationsip,然后实例化 EventModel ,它也会获得相同的关系,这是不正确的。 < p>如何才能使关系存储在子类中并且不被其他类继承? 即 需要在调用方法的类上存储 $ dynamicRelations 的副本,所以所有的孩子都不共享相同的关系?

谢谢!< / p>

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

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

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题