他们的关系是什么?
Gate 派生出 Policies
原因见:Providers/AuthServiceProvider.php 文件
其中有注册policies方法:
public function boot(){ $this->registerPolicies(); }
然后代码跟踪到 IlluminateFoundationSupportProvidersAuthServiceProvider.php 文件
<?php namespace IlluminateFoundationSupportProviders; use IlluminateSupportFacadesGate; use IlluminateSupportServiceProvider; class AuthServiceProvider extends ServiceProvider { /** * The policy mappings for the application. * * @var array */ protected $policies = []; /** * Register the application's policies. * * @return void */ public function registerPolicies() { foreach ($this->policies() as $key => $value) { Gate::policy($key, $value); } } /** * Get the policies defined on the provider. * * @return array */ public function policies() { return $this->policies; } }
可见注册方法:registerPolicies() 调用的是Gate里的policy()方法
所以说Providers 是出自Gate
为什么要派生出Providers?
原因是:直接使用Gate太麻烦了,而且不直观。
需要一个一个写Gate::defined("validate name","validate function.."),每有一个验证规则就要单独写一个 Gate::defined()
他们的使用方法?
Gate 门面:
Gate::allows('update articles', $article) Gate::denies('update articles', $article)
Controller:
$this->authorize('update articles', $article)
Blade 模板:
@can('update articles', $article)
@cannot('update articles', $article)
User Model 实例:
$user->can('update articles', $article)
$user->cannot('update articles', $article)
参考文章:https://learnku.com/articles/5479/introduce-laravel-authorization-mode-gate-and-policy