【问题标题】:Gate::define with constructor parameter in laravelGate::define 在 laravel 中使用构造函数参数
【发布时间】:2020-01-07 22:09:20
【问题描述】:

我正在使用 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


    }

AuthServiceProvider:

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

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

但是对于策略中的这段代码

  public function __construct($id)

我给出这个错误

无法解析的依赖解析 [Parameter #0 [ $id ]] in 类 App\Policies\BotPolicy

【问题讨论】:

    标签: php laravel


    【解决方案1】:

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

    我相信通过将__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;
    }
    

    【讨论】:

    • 我不明白为什么你需要在构造函数中使用该逻辑,如果需要,请解释原因。
    猜你喜欢
    • 2016-09-22
    • 2017-04-01
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-04
    • 1970-01-01
    相关资源
    最近更新 更多