Loading

关于Laravel Gate 和 Policies 的理解

他们的关系是什么?

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

posted @ 2019-12-13 14:12  ZJH_BLOGS  阅读(696)  评论(0编辑  收藏  举报