首页 > 解决方案 > Gate::define 在 laravel 中使用构造函数参数

问题描述

我正在使用 laravel Policy 和 Gate。

我需要__construct($id)在政策。

我的政策:

<?php

namespace App\Policies;

use App\Models\Button;
use App\User;
use Illuminate\Auth\Access\HandlesAuthorization;

class BotPolicy
{
    use HandlesAuthorization;

    /**
     * Create a new policy instance.
     *
     * @return void
     */
    public function __construct($id)
    {
        #First Step
        $this->bot = Bot::findOrFail($id);


        #Second Step
        if ( $this->bot->hasRole('admin') )
            return true;


        #Third Step
        if ( $this->bot->status != 1 )
            return false;
    }


    public function button(?User $user, $id)
    {
        #Fourth Step
        if ( $this->bot->account()->max >= $this->bot->button()->count() )
            return true;

        #Fail
        return false;
    }

}


我的控制器:


    public function create()
    {
        if ( Gate::denies('bot-button', request('id') ) )
            echo "NO";

        #SOME CODE HERE


    }

身份验证服务提供者:

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

        Gate::define('bot-button', 'App\Policies\BotPolicy@button');

但是对于策略中的此代码

  public function __construct($id)

我给这个错误

类 App\Policies\BotPolicy 中不可解析的依赖解析 [Parameter #0 [ $id ]]

标签: phplaravel

解决方案


首先,构造函数不是一种可以返回属性的方法,它只是一种在新创建的对象上调用的方法,通常用于设置属性等。

__constructor我相信通过将逻辑移至策略方法,您的策略可以这样编写。从而将 __constructor 全部删除,Laravel如果像这样加载依赖注入,它将尝试在容器中创建构造函数参数。

public function button(?User $user, $id)
{
    #First Step
    $this->bot = Bot::findOrFail($id);

    #Second Step
    if ( $this->bot->hasRole('admin') )
        return true;

    #Third Step
    if ( $this->bot->status != 1 )
        return false;

    #Fourth Step
    if ( $this->bot->account()->max >= $this->bot->button()->count() )
        return true;

    #Fail
    return false;
}

推荐阅读