簡體   English   中英

從Job處理程序調用Laravel控制器操作,並使用依賴注入

[英]Call Laravel controller action from Job handler, with dependency injections

我有中間件將任務放入隊列,將$ 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處理程序中正確初始化Request對象?

謝謝!

解決方案是將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
    }

}

希望它對某人有用,否則我將在稍后刪除整個帖子。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM