Laravel是否允许我们为模型添加多个策略?即考虑App\Providers\ASuthServiceProvider
的$policies
财产:
protected $policies = [ 'App\Team' => 'App\Policies\TeamPolicy', 'App\Team' => 'App\Policies\RoundPolicy', 'App\Team' => 'App\Policies\AnotherPolicy', ];
我还没有在一个应用程序中对它进行测试,因为即使它有效,我也会在这里提出一个类似的问题,关于这是否被视为不良行为或是否容易出现意外行为.
我的替代方案是一个非常混乱的策略,包含与几个控制器相关的策略,以camel case命名:
/** * Allows coach of Team and admin to see the Team management view. * Used in TeamManagementController * * @param App\User $user * @param App\Team $team * @return boolean */ public function manage(User $user, Team $team) { return $user->id === $team->user_id || $user->isAdmin(); } /** * Allows a coach to detach themself from a Team. * Used in TeamController * * @param App\User $user * @param App\Team $team * @return boolean */ public function detach(User $user, Team $team) { return $user->id === $team->user_id; } /** * Below function are used for controllers other than TeamController and TeamManagementController. * Reason: We need to authorize, based on a Team. Hence, using this Policy. */ /** * Allows coach of Team, as well as admin to view players of a Team. * Used in PlayerController * * @param App\User $user * @param App\Team $team * @return boolean */ public function indexPlayers(User $user, Team $team) { return $user->id === $team->user_id || $user->isAdmin(); } /** * Allows coach of Team, as well as admin to view players of a Team as an array. * Used in PlayerController * * @param App\User $user * @param App\Team $team * @return boolean */ public function fetchPlayers(User $user, Team $team) { return $user->id === $team->user_id || $user->isAdmin(); }
等等
您可以使用特征来分离策略的逻辑.
您可以TeamPolicy
使用基类中所需的各种方法创建基础,然后创建多个特征.
2> 小智..:该
$policies
变量使用模型的关键和值的策略.密钥是唯一的,因此您只能为每个模型设置一个策略.但是,您可以在多个模型上使用策略.在您的情况下,这
App\Policies\AnotherPolicy
是唯一将使用的.同时为多个模型分配相同的策略实际上取决于您想要做什么.基本上你不需要凌乱或粗糙的代码.因此,如果您为两个模型创建策略并且策略代码变得太大,则需要考虑创建另一个策略是否会使代码更简单/更少.