laravel-actions
laravel-actions copied to clipboard
Is there a way to get the job batch?
When using an action as a job, I need to be able to access the job batch. I was hoping asJob()
passed in the job, or that there would be $this->job
, or even a batch()
or getJobBatch()
method.
Reason is I need to be able to:
- Check if it has been batched
- Check if the batch has been cancelled
- Add jobs to the batch if it has been batched
...all normal things I need to do with batches.
❤️ your work.
While I'm still thinking of it - it would be convenient if the package checked if there is a batch, and if so add the "batch cancelled/return early/don't run handle/asJob" check.
It would be brilliant if Laravel handled it by default with a hook for onCancelled(Batch $batch)
. Maybe this package could do that with onJobCancelled(Batch $batch, ...$handleArgs)
which will run instead of asJob()
or handle()
when a batch is marked as cancelled.
Sorry, another stream of consciousness.
Can the package do dependency injection for methods like asJob()
, asCommand()
etc. For example, the package should know how to provide a Job
and ?Batch
typehint, and it should know how to provide the other args based on the handle
method.
public function handle(Team $team)
{
}
public function asJob(Job $job, ?Batch $batch, Team $team)
{
// and also support reverse order/inject last `public function asJob(Team $team, ?Batch $batch, Job $job)`
}
I actually only discovered this diving into the source code, but the ?Batch
typehint totally works if you make it the first argument. It is actually mention in the docs, just not on the asJob
page: https://laravelactions.com/2.x/dispatch-jobs.html#batching-jobs
You also can typehint a job decorator class as the first argument to get that as well. This should have access to all sorts of things. Queues, jobs, number of attempts, pretty much anything. Here's the relevant code from the JobDecorator
for reference:
if ($firstParameter->allowsNull() && $firstParameterClass === Batch::class) {
return [$this->batch(), ...$this->parameters];
} elseif (is_subclass_of($firstParameterClass, self::class) || $firstParameterClass === self::class) {
return [$this, ...$this->parameters];
} else {
return $this->parameters;
}
From: https://github.com/lorisleiva/laravel-actions/blob/4e60c9fbdfcea7d9977d882f3104c8996b43c169/src/Decorators/JobDecorator.php#L167
It's been awhile, so you may have already figured this out, but it may help someone in the future to find. I do think adding it to this page from the docs would be useful for reference: https://laravelactions.com/2.x/as-job.html#methods-provided