Skip to content

Instantly share code, notes, and snippets.

@juneym
Last active June 22, 2016 06:37
Show Gist options
  • Save juneym/61870f9476408bb7d7e2e08af8904bef to your computer and use it in GitHub Desktop.
Save juneym/61870f9476408bb7d7e2e08af8904bef to your computer and use it in GitHub Desktop.
PHP Generator as basis for co-routines
<?php
function getNextProduct($q, callable $f) {
$qptr = 0;
while (true) {
if ($qptr == count($q)) {
$qptr = 0;
}
yield $q[$qptr++];
$f($q);
}
}
function appendItemToQueue(array &$queue) {
$item = 'SKU' . rand(0,9999);
echo __METHOD__ . ": Adding item to queue: $item \n";
$queue[] = $item;
}
$queue = array('GM24ER', 'GM2CZ3', 'CMIROR1', 'CCIOP.1','KVL1234');
foreach (getNextProduct($queue, appendItemToQueue) as $sku) {
echo "Processing sku: ${sku} \n";
sleep(1);
}
------ Sample Run ---
shell> php queue-using-generator.php
Processing sku: GM24ER
appendItemToQueue: Adding item to queue: SKU8989
Processing sku: GM2CZ3
appendItemToQueue: Adding item to queue: SKU6431
Processing sku: CMIROR1
appendItemToQueue: Adding item to queue: SKU871
Processing sku: CCIOP.1
appendItemToQueue: Adding item to queue: SKU9266
Processing sku: KVL1234
appendItemToQueue: Adding item to queue: SKU3339
Processing sku: SKU8989
appendItemToQueue: Adding item to queue: SKU1803
Processing sku: SKU6431
appendItemToQueue: Adding item to queue: SKU8395
Processing sku: SKU871
appendItemToQueue: Adding item to queue: SKU1185
Processing sku: SKU9266
appendItemToQueue: Adding item to queue: SKU6602
Processing sku: SKU3339
appendItemToQueue: Adding item to queue: SKU697
Processing sku: SKU1803
appendItemToQueue: Adding item to queue: SKU3269
Processing sku: SKU8395
^C
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment