<?php
class Task
{
protected $follow_up = [];
protected $task_callback;
public function __construct($task_callback)
{
$this->task_callback = $task_callback;
}
public function addFollowUp(Task $follow_up)
{
$this->follow_up[] = $follow_up;
}
public function complete()
{
foreach($this->follow_up as $runnable) {
$runnable->run();
}
}
public function run()
{
$callback = $this->task_callback;
$callback($this);
}
}
$provided_task_scheduler_from_somewhere = function()
{
$tasks = [];
$global_message_thing = 'failed';
$second_global_message_thing = 'failed';
$task1 = new Task(function (Task $runner)
{
$something_in_closure = function() use ($runner) {
echo "running task one\n";
$runner->complete();
};
$something_in_closure();
});
/**
* use $global_message_thing as reference so we can manipulate it
* This will make sure that the follow up on this one knows the status of what happened here
*/
$second_follow_up = new Task(function(Task $runner) use (&$global_message_thing)
{
echo "second follow up on task one.\n";
$global_message_thing = "success";
$runner->complete();
});
/**
* Just doing things in random order to show that order doesn't really matter with a task scheduler
* just the follow ups
*/
$tasks[] = $task1;
$tasks[] = new Task(function(Task $runner)
{
echo "running task 2\n";
$runner->complete();
});
$task1->addFollowUp(new Task(function(Task $runner)
{
echo "follow up on task one.\n";
$runner->complete();
}));
$task1->addFollowUp($second_follow_up);
/**
* Adding the references to our "status" trackers here to know what to print
* One will still be on failed because we did nothing with it. this way we know it works properly
* as a control.
*/
$second_follow_up->addFollowUp(new Task(function(Task $runner) use (&$global_message_thing, &$second_global_message_thing) {
if($global_message_thing === "success") {
echo "follow up on the second follow up, three layers now, w00007!\n";
}
if($second_global_message_thing === "success") {
echo "you don't see this\n";
}
$runner->complete();
}));
return $tasks;
};
/**
* Normally you'd use some aggretating function to build up your tasks
* list or a collection of classes. I simulated that here with this callback function.
*/
$tasks = $provided_task_scheduler_from_somewhere();
foreach($tasks as $task) {
$task->run();
}