Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

upnorthal's avatar

Jobs - Previously known as Commands

Lets assume that I have a cart controller that is responsible for orchestrating the booking of tickets to a show.

There are multiple activities that need to occur including for example

  • check stock is still available
  • allocate tickets against individuals
  • determine whether discounts are applicable for the relevant ticket
  • initiate Stripe payment
  • send a confirmation email assuming the above works. (I understand this could be handled once an event was fired)

If I am going to move the above logic out of the controller into a Job, I don't get how I am supposed to get a response back from the Job class to the originating controller?

ie the first two items would definitely require a response to be sent back to the controller if they failed.

  • check stock is still available
  • allocate tickets against individuals

We wouldn't want them hanging around in a queue somewhere while the controller's view has already updated to the confirmation screen!

You can't issue a 'return' within the Job Handler class as it is marked void.

The only options available are

1: Remove the interface ShouldQueue so that the job is executed straight away

2: Fire a series of events at milestones (sounds complicated)

3: Just stick this kind of logic in a service class!

4: Somehow inject an instance of the calling Controller into the job itself, then update a flag on this. (not sure how practical that is but I'm sure I saw it mentioned somewhere)

Would be interested to hear anyone else's thoughts on this whole area.

0 likes
1 reply
d3xt3r's avatar

Think of job as something that you can defer. Given your question, definitely the first four doesn't qualify to be a background (asynchronous job). Better to place these logic directly into controller (or Model if you prefer) and let the final job be just sending the confirmation mail.

If you still want to stick with jobs but get things done synchronously, what I do is to make the base job class, add a method to return what is desired and in the handle method call the main method, i.e

/**
 * This method can be used to call the job synchronously and return the desired result
*/
public function run() {
    ... do your task here 
    return whatever is nedded ...
}

/**
 * This method will be called when job is fetched from quque. No return possible 
*/
public function handle() {
    $this->run();
}

This way i can schedule the job as well as run it synchronously, whenever i want.

1 like

Please or to participate in this conversation.