php 50 lines · 8 steps

A stable priority job queue in PHP

Wrapping SplPriorityQueue with a descending serial gives you priority ordering that stays FIFO for ties.

Explained by highlit
1<?php
2 
3namespace App\Queue;
4 
5use Closure;
6use SplPriorityQueue;
7 
8final class PriorityJobQueue
9{
10 private SplPriorityQueue $queue;
11 private int $serial = PHP_INT_MAX;
12 
13 public function __construct()
14 {
15 $this->queue = new SplPriorityQueue();
16 $this->queue->setExtractFlags(SplPriorityQueue::EXTR_DATA);
17 }
18 
19 public function push(Closure $job, int $priority = 0): void
20 {
21 $this->queue->insert($job, [$priority, $this->serial--]);
22 }
23 
24 public function isEmpty(): bool
25 {
26 return $this->queue->isEmpty();
27 }
28 
29 public function count(): int
30 {
31 return $this->queue->count();
32 }
33 
34 public function drain(): array
35 {
36 $results = [];
37 
38 while (!$this->queue->isEmpty()) {
39 $job = $this->queue->extract();
40 
41 try {
42 $results[] = $job();
43 } catch (\Throwable $e) {
44 $results[] = new FailedJob($e);
45 }
46 }
47 
48 return $results;
49 }
50}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A composite priority of [priority, serial] breaks ties deterministically so equal-priority jobs keep insertion order.
  2. 2Counting the serial downward makes earlier inserts rank higher when priorities match, preserving FIFO within a tier.
  3. 3Catching Throwable around each job lets the whole batch drain even when individual jobs fail.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A stable priority job queue in PHP — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code