简体   繁体   中英

Laravel: Passing a class name from a Controller to a Job

I'm trying to pass a certain class name from the controller to a job file through

Job::dispatch($className);

I've tried passing it as a string and passing it as a ClassName::class but none of these methods work

The code in the Job file looks something along the lines of this:

<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;


class BreakUpArraysJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $products;
    protected $jobName;

    public function __construct($products, $jobName)
    {
        $this->products = $products;
        $this->jobName = $jobName;
    }

    /**
     * Execute the jobName.
     *
     * @return void
     */
    public function handle()
    {
        $productArrays = array_chunk($this->products, 5000);

        foreach($productArrays as $productArray){
            $this->jobName::dispatch($productArray);
        }
    }
}

the $jobname variable is the className I'm trying to pass. I also need to note that I'm passing the classname of a different Job from the Controller, by which I mean the job handler is supposed to call another Job through the variable.

I do not think your syntax is working, an alternative approach would be to do it like this.

dispatch(new $this->jobName($productArray));

in your job construct add class Name that your var is instance of before $product like this:

 public function __construct(Product $products, $jobName)
    {
        $this->products = $products;
        $this->jobName = $jobName;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM