laravel-jobs

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Laravel Jobs

Laravel Jobs

Background jobs and event listeners: thin delegation layers to actions.
后台任务与事件监听器:作为业务逻辑的轻量委托层。

Core Concept

核心概念

jobs-listeners.md - Job patterns:
  • Jobs as thin delegation layers
  • Queue configuration
  • Retry logic and timeouts
  • Unique jobs
  • Job middleware
  • Event listeners
  • When to use jobs vs sync actions
jobs-listeners.md - 任务模式:
  • 任务作为轻量委托层
  • 队列配置
  • 重试逻辑与超时设置
  • 唯一任务
  • 任务中间件
  • 事件监听器
  • 何时使用任务而非同步操作

Pattern

模式示例

php
final class ProcessOrderJob implements ShouldQueue
{
    use Dispatchable, Queueable;

    public function __construct(
        public readonly int $orderId,
    ) {}

    public function handle(ProcessOrderAction $action): void
    {
        $order = Order::findOrFail($this->orderId);

        $action($order);
    }

    public function middleware(): array
    {
        return [new WithoutOverlapping($this->orderId)];
    }
}

// Listener
final class SendOrderConfirmationListener
{
    public function handle(OrderPlaced $event): void
    {
        SendOrderConfirmationJob::dispatch($event->order->id);
    }
}
Jobs delegate to actions. Keep domain logic in actions, not jobs.
php
final class ProcessOrderJob implements ShouldQueue
{
    use Dispatchable, Queueable;

    public function __construct(
        public readonly int $orderId,
    ) {}

    public function handle(ProcessOrderAction $action): void
    {
        $order = Order::findOrFail($this->orderId);

        $action($order);
    }

    public function middleware(): array
    {
        return [new WithoutOverlapping($this->orderId)];
    }
}

// Listener
final class SendOrderConfirmationListener
{
    public function handle(OrderPlaced $event): void
    {
        SendOrderConfirmationJob::dispatch($event->order->id);
    }
}
任务委托给业务动作类。将领域逻辑保存在动作类中,而非任务类本身。