Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Created May 23, 2019 14:51
Show Gist options
  • Save kobus1998/92e95650fdf0a0c7f74e185be3124a0b to your computer and use it in GitHub Desktop.
Save kobus1998/92e95650fdf0a0c7f74e185be3124a0b to your computer and use it in GitHub Desktop.
simple queue design
<?php
class QueueList
{
public function __construct()
{
$this->data = [];
}
public function isEmpty()
{
return empty($this->data);
}
public function add($data)
{
$this->data[] = $data;
return $this;
}
public function get()
{
if (empty($this->data))
{
return null;
}
return reset($this->data);
}
public function remove()
{
array_shift($this->data);
return $this;
}
}
interface Handler
{
public function handle($item);
}
class QueueDispatcher
{
public function __construct(QueueList $queue, Handler $handler)
{
$this->queue = $queue;
$this->handler = $handler;
}
public function execute()
{
while(!$this->queue->isEmpty()) {
$this->handler->handle(
$this->queue->get()
);
$this->queue->remove();
}
}
}
class Logger implements Handler
{
public function handle($item)
{
print_r($item);
echo "\n\n";
}
}
$queue = (new QueueList())
->add(1)
->add(2)
->add(3);
$handler = new Logger();
$dispatcher = (new QueueDispatcher($queue, $handler)->execute();
/*
result:
1
2
3
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment