【问题标题】:Laravel: Error getting response from a route in an Artisan CommandLaravel:从 Artisan 命令中的路由获取响应时出错
【发布时间】:2016-10-21 07:25:48
【问题描述】:

所以基本上我试图从我创建的自定义工匠命令中获取应用程序中路由的输出。我创建了请求并在句柄函数中使用路由器分派它,为了测试,只需将响应输出到控制台。

当我从控制台运行命令时,我总是收到一条错误消息,提示“类 web 不存在”,我认为“web”是中间件。

这是我第一次尝试这样做,但我被卡住了。如果您能检查我的代码并帮助我找出导致此错误的原因,我将不胜感激。

这是我的命令:

<?php

namespace APP\Console\Commands;

use Illuminate\Http\Request;
use Illuminate\Routing\Router;
use Illuminate\Events\Dispatcher;
use Illuminate\Console\Command;

class TestCmd extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'testcmd';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    protected $request;
    protected $router;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(Router $router)
    {
        parent::__construct();

        $this->router = $router;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $request = Request::create('test-route', 'GET');

        $this->info($this->router->dispatch($request));
    }
}

我得到的错误是:

ReflectionException in Container.php line 738: Class web does not exist

(这只是报错,输出的其实是控制台显示的默认laravel报错模板)

谢谢!


编辑

为了让我的问题更加清晰,我想用这段代码来描述我的目标。我想从命令行运行一个工匠命令,该命令将在我的应用程序中获取路由的响应并返回它。这些路由只是 API 端点。如果需要更多详细信息,请告诉我

【问题讨论】:

  • 由于您在此命令中没有使用任何单词 web,因此您的代码中的其他地方可能存在错误。例如,如果您运行 php artisan route:list,请查看是否收到此错误。您还可以对您的项目进行全面搜索,以查看您在哪里使用了 web 一词。
  • @TheFallen 感谢您的评论。实际上,错误是我在调度路线时得到的响应。因此,当然是应用于路由的中间件“网络”。问题是当您通常将浏览器指向一个 url 来访问路由时,它工作正常,但不能通过我的自定义命令工作。我希望我的命令调度路由并返回响应。我试过route:list,它工作正常。
  • 我现在看到了,但我不确定为什么会发生这个错误。我假设当您手动打开此 URL 时不会收到此错误,那么您是否尝试过使用 curl 而不是 Laravel 请求对象发出请求?

标签: laravel laravel-5.2 laravel-routing laravel-artisan


【解决方案1】:

试试这个

public function handle()
{
    $request = Request::create('test-route', 'GET');

    $kernel = app()->make(\Illuminate\Contracts\Http\Kernel::class);
    $response = $kernel->handle($request);
    $this->info($response->getOriginalContent());

}

【讨论】:

    猜你喜欢
    • 2018-09-09
    • 2015-04-06
    • 2017-03-26
    • 2017-01-18
    • 2020-03-17
    • 2019-01-14
    • 2018-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多