Laravel 能力在论点上是多态的吗?
Are Laravel abilities polymorphic on the argument?
我的理解是,使用策略定义的能力确实是多态的,这意味着:
Gate::allows('update', $post);
Gate::allows('update', $comment);
将调用不同的函数,如果两个对象是不同的类,并且注册了不同的策略:
protected $policies = [
Post::class => PostPolicy::class,
Comment::class => CommentPolicy::class,
];
虽然在我看来使用 $gate->define()
定义的能力 不是多态的 ,这意味着使用相同策略名称的两次调用将相互覆盖:
$gate->define('update', function ($user, $post) { /* THIS IS THROWN AWAY! */ });
$gate->define('update', function ($user, $comment) { /* the last one is kept */ });
这是正确的吗?
非多态示例文档中显示的能力名称 (update-post
、update-comment
) 与策略示例 (update
) 中显示的能力名称之间是否存在任何关系?
我的意思是,-post
后缀是Laravel加的还是推断出来的?或者它只是一个例子?
策略定义的能力和门定义的能力之间存在显着差异。
当你使用门的define
方法时,你的技能名称将为added to the abilities array of the gate,数组键为技能名称。如果您定义另一个具有相同名称的能力(例如 update
),它将覆盖旧的能力,因为不能有两个具有相同名称的数组键。所以在这种情况下,define($ability, $callback)
中的唯一标识符是能力。
相反,当您定义策略时class,能力名称是策略的实际方法名称。所以你可以有多个 classes 的方法命名相同(例如 update
),因为在这种情况下唯一标识符是 class 与第一个参数一起传递,所以 Post::class
.
在授权检查期间的某个时刻,Gate class 检查 if there's a policy associated with the first argument passed 并根据该评估调用策略方法或定义的能力回调。
所以想法是当使用 define
时你不能有两个同名的能力,因为下面是不可能的:
$abilities = [
'update' => $callback1,
'update' => $callback2, // this will override the first
]
就像使用 $policies
一样,您不能将多个策略关联到 class:
$policies = [
Post::class => PostPolicy::class,
Post::class => AnotherPostPolicy::class, // this will override the first one
];
因此,如果您想使用 update
作为多个模型的能力名称,只需使用策略即可。
这也应该回答你最后一个问题:Laravel 不推断或添加任何东西,能力名称是你传递给 define
的字符串或你在策略 [=45] 上定义的方法名称=]es.
我的理解是,使用策略定义的能力确实是多态的,这意味着:
Gate::allows('update', $post);
Gate::allows('update', $comment);
将调用不同的函数,如果两个对象是不同的类,并且注册了不同的策略:
protected $policies = [
Post::class => PostPolicy::class,
Comment::class => CommentPolicy::class,
];
虽然在我看来使用 $gate->define()
定义的能力 不是多态的 ,这意味着使用相同策略名称的两次调用将相互覆盖:
$gate->define('update', function ($user, $post) { /* THIS IS THROWN AWAY! */ });
$gate->define('update', function ($user, $comment) { /* the last one is kept */ });
这是正确的吗?
非多态示例文档中显示的能力名称 (update-post
、update-comment
) 与策略示例 (update
) 中显示的能力名称之间是否存在任何关系?
我的意思是,-post
后缀是Laravel加的还是推断出来的?或者它只是一个例子?
策略定义的能力和门定义的能力之间存在显着差异。
当你使用门的
define
方法时,你的技能名称将为added to the abilities array of the gate,数组键为技能名称。如果您定义另一个具有相同名称的能力(例如update
),它将覆盖旧的能力,因为不能有两个具有相同名称的数组键。所以在这种情况下,define($ability, $callback)
中的唯一标识符是能力。相反,当您定义策略时class,能力名称是策略的实际方法名称。所以你可以有多个 classes 的方法命名相同(例如
update
),因为在这种情况下唯一标识符是 class 与第一个参数一起传递,所以Post::class
.
在授权检查期间的某个时刻,Gate class 检查 if there's a policy associated with the first argument passed 并根据该评估调用策略方法或定义的能力回调。
所以想法是当使用 define
时你不能有两个同名的能力,因为下面是不可能的:
$abilities = [
'update' => $callback1,
'update' => $callback2, // this will override the first
]
就像使用 $policies
一样,您不能将多个策略关联到 class:
$policies = [
Post::class => PostPolicy::class,
Post::class => AnotherPostPolicy::class, // this will override the first one
];
因此,如果您想使用 update
作为多个模型的能力名称,只需使用策略即可。
这也应该回答你最后一个问题:Laravel 不推断或添加任何东西,能力名称是你传递给 define
的字符串或你在策略 [=45] 上定义的方法名称=]es.