doulin3510 2019-06-12 00:47
浏览 501

PHP 7.2 + Laravel 5.8:调用Trait中定义的父方法,该方法在使用此特征的类中调用父方法时被覆盖

It may be hard to explain this case via title so let me put it here.

I had to use Laravel Boilerplate. It uses UUIDs for models. It has a trait that when User model is being created, it adds UUID.

protected static function boot() // this is in the trait
{
    parent::boot();

    static::creating(function ($model) {
        $model->{$model->getUuidName()} = PackageUuid::generate(4)->string;
    });
}

My Eloquent User uses this trait. Everything was working but one day I had to add global scope to User so I defined in the User class:

protected static function boot()
{
    parent::boot();

    static::addGlobalScope(new UserScopeSalesContactAdmin());
}

enter image description here

I totally missed that. Now my global scope works but UUID is ignored. I obviously know why this happens. I'm not the author of the Boilerplate and I would architecture this in a different way but it's a nice educational case hence my question:

How can I change my code the way that both my global scope works as well as UUID? I could simply move my addGlobalScope to the trait but it's obviously stupid idea as scope has nothing to do with UUID hence it violates the OOP rule.

edit:

I did other way around: I copied:

static::creating(function ($model) {
     $model->{$model->getUuidName()} = PackageUuid::generate(4)->string;
});

to the boot method in the User but still I consider this as a duplication…

  • 写回答

2条回答 默认 最新

  • dongque3797 2019-06-12 04:22
    关注

    You can write your own trait. But instead of boot() define boot<TraitName>():

    trait HasUuid
    {
        protected static function bootHasUuid()
        {
            static::creating(function ($model) {
                $model->{$model->getUuidName()} = PackageUuid::generate(4)->string; 
            });
        }
    }
    

    This way you don't need to override boot().

    Laravel will call the special boot method of traits based on the naming scheme described above. It's just not well documented functionality...

    评论

报告相同问题?

悬赏问题

  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)