Laravel now supports the use of enums with fallback values directly in the onQueue
method of Bus facade, without manually accessing the value
attribute of the enumeration. This improvement creates cleaner and more expressive code when handling job chains and queues.
This enhancement is especially useful when building complex job pipelines that need to be directed to different queues based on priority, resource requirements, or business logic.
use App\Enums\QueueType; // 直接使用枚举,无需 ->value Bus::chain($jobs) ->onQueue(QueueType::Background) ->dispatch();
The following is an actual example of implementing a document processing system:
<?php namespace App\Enums; enum ProcessingQueue: string { case Immediate = 'realtime'; case Standard = 'default'; case Batch = 'batch-process'; case LowPriority = 'low-priority'; } namespace App\Services; use App\Enums\ProcessingQueue; use App\Jobs\ProcessDocument; use App\Jobs\GenerateThumbnail; use App\Jobs\ExtractMetadata; use App\Jobs\NotifyUser; use App\Models\Document; use Illuminate\Support\Facades\Bus; class DocumentProcessor { public function process(Document $document, bool $isPriority = false) { $queue = $isPriority ? ProcessingQueue::Immediate : ProcessingQueue::Standard; Bus::chain([ new ProcessDocument($document), new ExtractMetadata($document), new GenerateThumbnail($document), new NotifyUser($document->user, 'Document processing complete') ]) ->onQueue($queue) ->dispatch(); return $document; } public function batchProcess(array $documentIds) { foreach ($documentIds as $id) { $document = Document::find($id); Bus::chain([ new ProcessDocument($document), new GenerateThumbnail($document) ]) ->onQueue(ProcessingQueue::Batch) ->dispatch(); } } }
This enhancement simplifies queue implementation while maintaining type safety and improving code readability.
The above is the detailed content of Cleaner Queue Chains with Laravel's Enum Integration. For more information, please follow other related articles on the PHP Chinese website!