PHP中是否有类似特性的接口?
我经常发现自己希望能够让 trait 实现一个接口,这样当我将 trait 添加到类中时,我可以知道满足了 trait 的要求。例如,在 Laravel 中,我将为我的许多关系创建特征,如下所示:
trait HasOwner
{
public function owner()
{
return $this->belongsTo(User::class);
}
}
在 Laravel 的情况下,我可以非常确定我添加它的每个模型都将有一个 ownsTo 方法,但是我仍然觉得我应该能够强制执行这个。
我知道强制执行此操作的唯一方法是使用 HasOwnerInterface 或 HasRelationshipsInterface 来支持它,但事实上,当我添加特性时未能添加它会防止它发出吱吱声,感觉就像在车上安装了安全气囊,但您需要这样做每次启动发动机时打开。
这是我认为将是完美的:
trait HasOwner expects RelationshipInterface
{
public function owner()
{
return $this->belongsTo(User::class);
}
}
interface RelationshipInterface
{
public function belongsTo(Model $model): Relationship;
}
class Property implements RelationshipInterface
{
use HasOwner;
}
我应该为此使用另一种设计模式,还是我应该鼓起勇气,开始与 PHP 核心团队为此而战以添加它?