Created
May 23, 2019 14:51
-
-
Save kobus1998/92e95650fdf0a0c7f74e185be3124a0b to your computer and use it in GitHub Desktop.
simple queue design
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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