php - 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 ]]
解决方案
首先,构造函数不是一种可以返回属性的方法,它只是一种在新创建的对象上调用的方法,通常用于设置属性等。
__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;
}
推荐阅读
- json - 如何制作一个结构来解码 Swift 中的 JSON 结构?
- reactjs - 动态导入不适用于 Webpack 4 + React + @loadable/component
- arrays - Pytorch U-net 分割模型的“ValueError:轴与数组错误不匹配”可能是什么原因?
- php - PHP 对于每个帮助,请
- python - Markdown Preview 增强版 VSCode 运行代码块
- python - Matplotlib 多项式回归 - 显示的线条过多
- unity3d - Unity - 防止子对象被拖到父对象之外
- javascript - Chart.js 包含变量时不显示
- nginx - 请求远程帮助以帮助安装具有静态 IP 和 LetsEncrypt 的 AKS
- angular - 嵌套和角度应用程序之间的 Nrwl / Nx 依赖错误