php - 从作业处理程序调用 Laravel Controller 操作,使用依赖注入(inject)

标签 php laravel

我有将任务放入队列的中间件,将 $actionName 和 GET/POST 参数传递给作业构造函数。这段代码:

$actionName = last(explode('@', $request->route()->getActionName()));
$arguments = $request->query->all();
$job = new HandleApiRequest($actionName, $arguments);
dispatch($job);

然后,在 Job 处理程序中,我想使用传递的参数调用 Controller 方法(参数在 Job 构造函数中初始化,不用担心)。这是一个代码:

$data = app()->call(ApiController::class . '@' . $this->method, $this->arguments);

问题是我无法在调用的 Controller 及其服务中使用请求对象 (Illuminate\Http\Request)。似乎 Controller 进入了无限循环,并且在它的服务中它只是空的。然后我在工作人员的控制台中看到这个日志:

[Illuminate\Contracts\Container\BindingResolutionException]                                                      
  Target [App\Http\Requests\Request] is not instantiable while building [App\Http\Controllers\Api\ApiController].  

问题是,如何在 Job 处理程序中正确初始化 Request 对象?

谢谢!

最佳答案

解决方案是将 Request 对象注入(inject)处理程序方法,并用中间件传递的数据填充它:

class HandleApiRequest extends Job implements ShouldQueue
{
    use InteractsWithQueue, SerializesModels;

    private $method;
    private $arguments;

    public function __construct(string $method, array $arguments)
    {
        $this->method = $method;
        $this->arguments = $arguments;


    }

    public function handle(ErrorService $error_service, Request $request)
    {
        /*
         * Fill our empty request object with arguments passed by middleware.
         * It's later will be used in controller and services.
         */
        $request->query->add($this->arguments);
        $data = app()->call(ApiController::class . '@' . $this->method);

        //use $data here
    }

}

希望它对某些人有用,否则我稍后会删除整个线程。

关于php - 从作业处理程序调用 Laravel Controller 操作,使用依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37397093/

相关文章:

php - Laravel (5.3) Eloquent - 关系问题

php - 将字符串变量插入数组

php - MySQL 查询中的 SORT BY 不会改变查询结果数组中的顺序

php - 无法创建迁移 Laravel

php - 调用未定义的方法 MongoDB\Driver\ReadConcern::isDefault()

PHP:使用 "new"初始化数组与不使用 0x104567910 初始化数组有什么区别?

javascript - 在 while 循环中从一种表单发布数据

reactjs - 如何使用 React 连接 Laravel Websocket?

php - Laravel 5 空 cookie 崩溃

php - 在 laravel 4 中提交表单后重定向到联系人页面