Gate 派生出 Policies

原因见:Providers/AuthServiceProvider.php 文件

其中有注册policies方法:

public function boot(){
    $this->registerPolicies();
}

然后代码跟踪到 \Illuminate\Foundation\Support\Providers\AuthServiceProvider.php 文件

<?php

namespace Illuminate\Foundation\Support\Providers;

use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;

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

相关文章:

  • 2021-09-10
  • 2021-11-11
  • 2021-04-28
  • 2021-07-22
  • 2021-11-13
  • 2021-06-16
  • 2021-09-15
  • 2021-10-03
猜你喜欢
  • 2021-12-03
  • 2021-08-17
  • 2021-04-26
  • 2021-12-05
  • 2022-12-23
  • 2022-12-23
  • 2021-09-08
相关资源
相似解决方案