有没有办法在 PHP 中扩展 trait?

我想使用一个现有的 trait的功能,并在其上创建我自己的 trait,然后将其应用到类中。

我想扩展 Laravel SoftDeletes trait 以使 SaveWithHistory发挥作用,这样它将创建一个记录的副本作为一个已删除的记录。我还想用 record_made_by_user_id字段扩展它。

34969 次浏览

Yes, there is. You just have to define new trait like this:

trait MySoftDeletes
{
use SoftDeletes {
SoftDeletes::saveWithHistory as parentSaveWithHistory;
}


public function saveWithHistory() {
$this->parentSaveWithHistory();


//your implementation
}
}

I have different approach. ParentSaveWithHistory is still applicable method in this trait so at least should be defined as private.

trait MySoftDeletes
{
use SoftDeletes {
saveWithHistory as private parentSaveWithHistory;
}


public function saveWithHistory()
{
$this->parentSaveWithHistory();
}
}

Consider also 'overriding' methods in traits:

use SoftDeletes, MySoftDeletes {
MySoftDeletes::saveWithHistory insteadof SoftDeletes;
}

This code uses method saveWithHistory from MySoftDeletes, even if it exists in SoftDeletes.