We are now going to implement the queue data structure using a PHP array. We have already seen that we can use the array_push() function to add an element at the end of the array. In order to remove the first element of the array, we can use the array_shift() function of PHP, and for the peek function, we can use the current() function of PHP. Here is how the code will look, based on our discussion:
class AgentQueue implements Queue {
private $limit;
private $queue;
public function __construct(int $limit = 20) {
$this->limit = $limit;
$this->queue = [];
}
public function dequeue(): string {
if ($this->isEmpty()) {
throw new UnderflowException('Queue is empty');
} else {
return array_shift($this->queue);
}
}
public function enqueue(string $newItem) {
if (count($this->queue) < $this->limit) {
array_push($this->queue, $newItem);
} else {
throw new OverflowException('Queue is full');
}
}
public function peek(): string {
return current($this->queue);
}
public function isEmpty(): bool {
return empty($this->queue);
}
}
Here, we are maintaining the same principle we did for the stack. We want to define a fixed-size queue, with checking of overflow and underflow. In order to run the queue implementation, we can consider using it as an agent queue for a call center application. Here is the code to utilize our queue operations:
try {
$agents = new AgentQueue(10);
$agents->enqueue("Fred");
$agents->enqueue("John");
$agents->enqueue("Keith");
$agents->enqueue("Adiyan");
$agents->enqueue("Mikhael");
echo $agents->dequeue()." ";
echo $agents->dequeue()." ";
echo $agents->peek()." ";
} catch (Exception $e) {
echo $e->getMessage();
}
This will produce the following output:
Fred
John
Keith