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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A composite priority of [priority, serial] breaks ties deterministically so equal-priority jobs keep insertion order.
- 2Counting the serial downward makes earlier inserts rank higher when priorities match, preserving FIFO within a tier.
- 3Catching Throwable around each job lets the whole batch drain even when individual jobs fail.
Related explainers
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-stable-priority-job-queue-in-php-explained-php-bb69/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.