Skip to content

Instantly share code, notes, and snippets.

@frankiejarrett
Last active July 7, 2023 19:24
Show Gist options
  • Save frankiejarrett/99566a851e20ca4d1c98dd0fb99e5d84 to your computer and use it in GitHub Desktop.
Save frankiejarrett/99566a851e20ca4d1c98dd0fb99e5d84 to your computer and use it in GitHub Desktop.
How to run Laravel Jobs like Actions with return values, best of both worlds
<?php
namespace App\Jobs;
use Exception;
use Throwable;
class ExampleJob extends BaseJob
{
public int $number;
public function __construct(string $number)
{
$this->number = $number;
}
public function handle(): int
{
echo 'the job is running';
try {
throw new Exception('Whoops, something went wrong.');
} catch (Throwable $e) {
$this->fail($e);
return 911;
}
return $this->number;
}
public function failed(Throwable $e): void
{
echo 'handle the failed job';
throw $e;
}
}
<?php
namespace App\Jobs;
use Illuminate\Bus\Batchable;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Fluent;
use Throwable;
abstract class BaseJob implements ShouldQueue
{
use Batchable,
Dispatchable,
InteractsWithQueue,
Queueable,
SerializesModels;
public bool $deleteWhenMissingModels = true;
public int $tries = 3;
abstract public function handle();
public function fail(Throwable $e): void
{
if ($this->job) {
$this->job->fail($e);
} else {
throw $e;
}
}
public function failed(Throwable $e): void
{
throw $e;
}
public function backoff(): array
{
return [0, 2];
}
public static function make(...$args): static
{
return new static(...$args);
}
public static function run(...$args): mixed
{
$instance = static::make(...$args);
try {
return $instance->handle();
} catch (Throwable $e) {
$instance->failed($e);
}
}
public static function runIf($condition, ...$args): mixed
{
return $condition ? static::run(...$args) : new Fluent;
}
public static function runUnless($condition, ...$args): mixed
{
return static::runIf(! $condition, ...$args);
}
}
<?php
// Run as an object (no retries)
$result = ExampleJob::run(42);
$result = ExampleJob::runIf(true, 42);
$result = ExampleJob::runUnless(false, 42);
// Dispatch to the queue (with retries)
ExampleJob::dispatch(42);
ExampleJob::dispatchIf(true, 42);
ExampleJob::dispatchUnless(false, 42);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment