Skip to Content
Course content

183: Implementing a Queue in PHP

Click on the "Edit" button in the top corner of the screen to edit your slide content.

In a perfect world, every piece of code we write would execute instantly. In the real world, we have things like third-party APIs, heavy image processing, and SMTP servers that take forever to respond. If you make a user wait for an email to actually send before their "Thank You" page loads, they're going to think your site is frozen. That's where a queue comes in.

Now, if we were building a massive enterprise system, I'd tell you to use Redis or RabbitMQ. But to understand the mechanics of a queue—the First-In-First-Out (FIFO) principle—it's best to build one ourselves using PHP's array functions. We're going to build a simple email dispatcher queue.

Defining the queue structure

I want a class that encapsulates the queue logic so I don't have to manually manage arrays throughout my application. I'll start by creating a basic class with a private array to hold our "jobs."

class EmailQueue {
    private array $queue = [];

    public function enqueue(string $emailAddress, string $message): void {
        $this->queue[] = [
            'email' => $emailAddress,
            'message' => $message,
            'timestamp' => time()
        ];
    }
}

The enqueue method is straightforward. I'm just appending a new associative array to the end of my $queue list. Each entry acts as a "job" waiting to be processed.

Trying to process the jobs

Next, I need a way to get those emails out of the queue and "send" them. I'll write a dequeue method that returns the next job in line.

    public function dequeue(): ?array {
        if ($this->isEmpty()) {
            return null;
        }
        return array_pop($this->queue);
    }

    public function isEmpty(): bool {
        return empty($this->queue);
    }

I just ran a quick test with this, and I realized I messed up. I added "Welcome Email" then "Password Reset Email," but when I called dequeue, it gave me the "Password Reset" first. That's not a queue; that's a stack (Last-In-First-Out). My bad. I used array_pop, which grabs the last element added.

Correcting the FIFO logic

To make this a true queue, I need to take the item from the front of the array, not the back. PHP has a perfect function for this: array_shift. It removes the first element and shifts everything else down one index.

    public function dequeue(): ?array {
        if ($this->isEmpty()) {
            return null;
        }
        // Use array_shift instead of array_pop to maintain FIFO order
        return array_shift($this->queue);
    }

Now, the first email added is the first one processed. This is critical. You don't want a user to receive their "Account Deleted" confirmation before their "Welcome" email just because of the order they were processed.

Running the dispatcher

To wrap this up, let's see it in action. I'll simulate a loop that processes the queue until it's empty. In a real app, this would probably be a cron job or a background worker script.

$dispatcher = new EmailQueue();

// Adding some jobs
$dispatcher->enqueue('user1@example.com', 'Welcome to the platform!');
$dispatcher->enqueue('user2@example.com', 'Your order has shipped.');
$dispatcher->enqueue('user3@example.com', 'Password reset request.');

echo "Starting email processing...\n";

while (!$dispatcher->isEmpty()) {
    $job = $dispatcher->dequeue();
    echo "Sending email to {$job['email']}: {$job['message']}\n";
    // In a real scenario, mail() or a PHPMailer call would go here
}

echo "All emails sent!";

The logic is simple, but the impact is huge. By decoupling the request to send an email from the actual act of sending it, you've just made your application significantly more responsive.




📋 Practical Task

Build a Priority-Based Task Queue

Your goal is to extend the queue concept. Instead of a simple FIFO queue, create a TaskQueue class where tasks can be added with a priority level (e.g., 'high', 'medium', 'low').

  • Implement an enqueue method that accepts a task description and a priority.
  • Implement a dequeue method that always returns the 'high' priority tasks first, regardless of when they were added. If no high priority tasks exist, move to 'medium', then 'low'.
  • Ensure that within the same priority level, the tasks are still processed in FIFO order.
  • Test your implementation by adding three tasks in mixed order (low, high, medium) and verify that they are dequeued in the order of priority.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.