【发布时间】:2022-09-23 04:24:53
【问题描述】:
我有多个策略类。
并且这些策略\'update, delete, restore 函数具有相同的逻辑评估,即检查经过身份验证的用户是否拥有资源。
例如,我有一个邮政和一个评论模型。
那么对于邮政政策和评论政策,他们的update, delete, restore 函数都将具有:
public function update(User $user, Post $post)
{
return $user->id == $post->user_id;
}
public function delete(User $user, Post $post)
{
return $user->id == $post->user_id;
}
public function restore(User $user, Post $post)
{
return $user->id == $post->user_id;
}
// Also the same with CommentPolicy
有了这个,我还不如有这样的特质:
trait AuthorizableTrait
{
public function authorize(User $user, Resource $resource)
{
return $user->id == $resource->user_id;
}
}
所以,我的问题是,是否可以在 trait 中注入当前模型的动态实例,例如,Post 和 Comment 模型现在将变为 Resource?如果是这样,如何?