Status message

Maintenant, vous regardez: Implementing a queue

Implementing a queue

if we define an interface for a queue, it will look like this:

  1. interface Queue {
  2. public function enqueue(string $item);
  3. public function dequeue();
  4. public function peek();
  5. public function isEmpty();
  6. }

we are going to implement the queue using a PHP array:

  1. class AgentQueue implements Queue {
  2. private $limit;
  3. private $queue;
  4.  
  5. public function __construct(int $limit = 20) {
  6. $this->limit = $limit;
  7. $this->queue = [];
  8. }
  9.  
  10. public function dequeue(): string {
  11. if ($this->isEmpty()) {
  12. throw new UnderflowException('Queue is empty');
  13. } else {
  14. return array_shift($this->queue);
  15. }
  16. }
  17. public function enqueue(string $newItem) {
  18. if (count($this->queue) < $this->limit) {
  19. array_push($this->queue, $newItem);
  20. } else {
  21. throw new OverflowException('Queue is full');
  22. }
  23. }
  24.  
  25. public function peek(): string {
  26. return current($this->queue);
  27. }
  28.  
  29. public function isEmpty(): bool {
  30. return empty($this->queue);
  31. }
  32. }
  33.  
  34. try {
  35. $agents = new AgentQueue(10);
  36. $agents->enqueue("Fred");
  37. $agents->enqueue("John");
  38. $agents->enqueue("Keith");
  39. $agents->enqueue("Adiyan");
  40. $agents->enqueue("Mikhael");
  41. echo $agents->dequeue()."\n";
  42. echo $agents->dequeue()."\n";
  43. echo $agents->peek()."\n";
  44. } catch (Exception $e) {
  45. echo $e->getMessage();
  46. }