PHP
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions
-
Section 4: Object-Oriented PHP
-
Section 5: Working with Data
-
Section 6: Modern PHP (PHP 8)
-
Section 7: Working with Files and Networking
-
Section 8: Common PHP Frameworks Overview
-
Section 9: Tooling and Ecosystem
-
Section 10: Practical Projects
-
Section 11: Interview Practice
-
Section 12: More Standard Library
-
Section 13: Data Structures and Algorithms in PHP
-
Section 14: More Practice Exercises
-
Section 15: More Security and Best Practices
-
Section 16: More Testing and Tooling
-
Section 17: WordPress-Style CMS Concepts
-
Section 18: Advanced OOP Practice
-
Section 19: More Web Fundamentals
-
Section 20: Database Practice
-
Section 21: PHP Manual: Array Functions
-
Section 22: PHP Manual: Date and Calendar Functions
-
Section 23: PHP Manual: Filesystem and Directory Functions
-
Section 24: PHP Manual: Filter and Var Handling
-
Section 25: PHP Manual: Math Functions
-
Section 26: PHP Manual: JSON and XML
-
Section 27: PHP Manual: Network and Stream Functions
-
Section 28: PHP Manual: Error and Exception Handling
-
Section 29: PHP Manual: Output Control and Misc
-
Section 30: PHP Manual: FTP, Zip, and Mail
-
Section 31: Modern PHP Frameworks Deep Dive
-
Section 32: PHP Design Patterns
-
Section 33: More Practice Exercises
-
Section 34: PHP Performance and Deployment
-
Section 35: More Interview Practice
-
Section 36: More PHP Standard Library
-
Section 37: PHP Concurrency and Async
-
Section 38: More Web Development Practice
-
Section 39: PHP Testing Deep Dive
-
Section 40: Composer and Package Development
-
Section 41: PHP Security Deep Dive
-
Section 42: More Practical Projects
-
Section 43: Legacy PHP Maintenance
-
Section 44: More Algorithm Practice
-
Section 45: Final Practice and Review
-
Section 46: PHP for E-Commerce Patterns
-
Section 47: PHP API Design Deep Dive
-
Section 48: PHP Caching Strategies
-
Section 49: PHP Queue and Background Jobs
-
Section 50: PHP Multi-Tenancy Patterns
-
Section 51: PHP Real-Time Features
-
Section 52: PHP CMS and Content Modeling
-
Section 53: PHP Internationalization
-
Section 54: More Framework-Specific Practice
-
Section 55: PHP Legacy Code Refactoring
-
Section 56: More Practice Projects Round 2
-
Section 57: PHP Command-Line Applications
-
Section 58: PHP and Microservices
-
Section 59: More Interview and Review Round 2
183: Implementing a Queue in PHP
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
enqueuemethod that accepts a task description and a priority. - Implement a
dequeuemethod 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.
There are no comments for now.