For example I want to create two separate projects that should communicate through some queue (rabbitmq for instance).
Do I understand correctly that I just have to create some job in producer project with empty handle()
method to prevent handling by itself, and create another job with the same name in consumer project and run php artisan queue:listen
. So when I do SomeJob::dispatch($payload);
in producer service, rabbitmq will receive this job. After that queue worker that looking for incoming messages will receive message and will call handle()
in corresponding SomeJob
in consumer project. Did I understand mechanism correctly? The main thing that slips away from me is how worker knows what handle()
method to call especially if we use different Job names in different projects (is it possible)?
Currently I am making consumer mechanism in project that will receive messages from queue.
I think you understand how jobs work in rabbitmq.
Most important is that both apps have job with a same name. Job class in producer need only constructor. Handle function run only on consumer.
I don't think you can have different job names on producer and consumer.
If you need more "free" communication and you do not want to have class for each event, you can make some generic job class as "EventJob" that will act as router.
But, keep it simple:
Here is an example of job that runs when invoice is created:
Jobs/InvoiceCreatedJob.php. - on producer
/*
* This job is called from InvoiceObserver:
* public function created(Invoice $invoice): void
* { InvoiceCreatedJob::dispatch($invoice->toArray());}
*/
class InvoiceCreatedJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct(public array $data)
{}
}
Jobs/InvoiceCreatedJob.php. - on consumer
class InvoiceCreatedJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct(public array $data)
{}
public function handle(): void
{
//some code to handle invoice data
}
}