我有中间件将任务放入队列,将$ actionName和GET / POST参数传递给Job构造函数。这段代码:
$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及其服务中使用Request对象( Illuminate \ Http \ Request )。似乎控制器进入无限循环,并在其中服务它只是空的。然后我在worker的控制台中看到这个日志:
[Illuminate\Contracts\Container\BindingResolutionException]
Target [App\Http\Requests\Request] is not instantiable while building [App\Http\Controllers\Api\ApiController].
问题是,如何在Job handler中正确初始化Request对象?
谢谢!
答案 0 :(得分:5)
解决方案是将Request对象注入到handler方法中,并用从中间件传递的数据填充它:
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
}
}
希望它对某些人有用,否则我将在以后删除整个帖子。