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 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?
  • ¥50 invest生境质量模块