dsrjs86444 2019-04-30 00:34
浏览 46
已采纳

如何将请求注入Laravel的Facade类?

So I have the following class that's a facade:

namespace App\Helpers;

use App\Http\Requests\HomepageRequest;

class Params {

    public function __construct(HomepageRequest $request) {

    }

Then I have the ParamsServiceProvider class which instantiates the facade class on script startup:

public function register()
{
    //
    App::bind('params', function() {
        return new Params();
    });
}

edit: here is the actual facade for the Params class

use Illuminate\Support\Facades\Facade;

class Params extends Facade {
    protected static function getFacadeAccessor() {
        return 'params';
    }
}

This all works fine, the class is instantiated properly, however, it doesn't seem to inject the request object in the constructor like it would in a controller class. Is there a way to inject the request into a facade class like you would in a controller? With the current code, I get the following error:

Too few arguments to function App\Helpers\Params::__construct(), 0 passed in /var/www/v4api/html/app/Providers/ParamsServiceProvider.php on line 21 and exactly 1 expected

I want to avoid having to manually pass the request input into the class and just have it automatically be injected in the constructor. Any help that you guys can give would be appreciated!

  • 写回答

3条回答 默认 最新

  • dswe30290 2019-04-30 00:49
    关注

    Looks like this worked out:

    In the ParamsServiceProvider, instead of using App::bind to instantiate the Params class, do this instead:

    public function register()
    {
        App::alias(Params::class, 'params');
    }
    

    then the request object will be injected properly into the facade.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题