Skip to content

Instantly share code, notes, and snippets.

@ghostwriter
Created July 4, 2025 18:57
Show Gist options
  • Save ghostwriter/10767770aa67f5ed4688117a0176efca to your computer and use it in GitHub Desktop.
Save ghostwriter/10767770aa67f5ed4688117a0176efca to your computer and use it in GitHub Desktop.
Cooperative Multitasking with PHP Fibers
<?php
final class Deployment
{
/**
* @param array<string, list<string>> $pipelineStages
*/
public function run(array $pipelineStages): void
{
$pipeline = new Fiber(function (array $pipelineStages): string {
Fiber::suspend('Pipeline initialized.');
foreach ($pipelineStages as $stage => $steps) {
foreach ($steps as $step) {
Fiber::suspend("Stage '{$stage}': step '{$step}' completed.");
}
}
return 'Deployment successful.';
});
$monitor = new Fiber(function (): string {
Fiber::suspend('Monitoring system initialized.');
while (true) {
Fiber::suspend('System health: OK.');
}
});
$pipeline->start($pipelineStages);
$monitor->start();
while (! $pipeline->isTerminated()) {
printf("[Pipeline] %s\n", $pipeline->resume());
printf("[Monitor] %s\n", $monitor->resume());
}
$result = $pipeline->getReturn();
printf("[Result] %s\n", $result);
}
}
$stages = [
'build' => ['compile', 'lint', 'optimize'],
'test' => ['unit', 'integration', 'e2e'],
'package' => ['zip', 'sign'],
'deploy' => ['upload', 'release', 'notify'],
];
(new Deployment())->run($stages);

Output

Pipeline] Stage 'build': step 'compile' completed.
[Monitor]  System health: OK.
[Pipeline] Stage 'build': step 'lint' completed.
[Monitor]  System health: OK.
[Pipeline] Stage 'build': step 'optimize' completed.
[Monitor]  System health: OK.
[Pipeline] Stage 'test': step 'unit' completed.
[Monitor]  System health: OK.
[Pipeline] Stage 'test': step 'integration' completed.
[Monitor]  System health: OK.
[Pipeline] Stage 'test': step 'e2e' completed.
[Monitor]  System health: OK.
[Pipeline] Stage 'package': step 'zip' completed.
[Monitor]  System health: OK.
[Pipeline] Stage 'package': step 'sign' completed.
[Monitor]  System health: OK.
[Pipeline] Stage 'deploy': step 'upload' completed.
[Monitor]  System health: OK.
[Pipeline] Stage 'deploy': step 'release' completed.
[Monitor]  System health: OK.
[Pipeline] Stage 'deploy': step 'notify' completed.
[Monitor]  System health: OK.
[Pipeline] 
[Monitor]  System health: OK.
[Result]   Deployment successful.

// https://3v4l.org/8GI6K

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment