由于 Red 发布的这种很酷的可能性,我编写了一个小型实用程序类,它提供了一个队列,您可以在其中添加闭包以供以后执行:
<?php
namespace Company\Project\Utilities;
/**
* Class ContinueUtility
*
* @package Company\Project\Utilities
*/
class ContinueUtility {
/**
* Stored tasks
* @var array
*/
static protected $tasks = array();
/** Constant for new line in HTTP Header */
const HEADER_NEW_LINE = "\r\n";
/**
* Add task (closure/function) to queue, with set arguments
*
* @param \Closure $task
* @param array $arguments
* @return void
*/
public static function addTask(\Closure $task, array $arguments = array()) {
self::$tasks[] = array(
'closure' => $task,
'arguments' => $arguments
);
}
/**
* Returns TRUE if tasks has been set, otherwise FALSE
*
* @return boolean
*/
public static function hasTasks() {
return !empty(self::$tasks);
}
/**
* Clear all previous set tasks
*
* @return void
*/
protected static function clearTasks() {
self::$tasks = array();
}
/**
* Execute all previous set tasks
*
* @return void
*/
protected static function executeTasks() {
foreach (self::$tasks as $task) {
call_user_func_array($task['closure'], $task['arguments']);
}
}
/**
* Execute and clear all previous set tasks
*
* @return void
*/
public static function executeAndClearTasks() {
self::executeTasks();
self::clearTasks();
}
/**
* Closes the HTTP connection to client immediately and outputs given string.
*
* @param string $instantOutput
* @return void
*/
public static function closeConnection($instantOutput = '') {
set_time_limit(0);
ignore_user_abort(TRUE);
header('Connection: close' . self::HEADER_NEW_LINE);
header('Content-Encoding: none' . self::HEADER_NEW_LINE);
ob_start();
echo $instantOutput;
$size = ob_get_length();
header('Content-Length: ' . $size, TRUE);
ob_end_flush();
ob_flush();
flush();
}
}
这是将新任务添加到队列的方式:
use Company\Project\Utilities\ContinueUtility;
$a = 4;
$b = 5;
ContinueUtility::addTask(function($a, $b){
sleep(5);
$c = a + b;
file_put_contents(__DIR__ . '/whatever.log', $a . '+' . $b . '=' . $c);
}, array(
$a, $b
));
这就是您触发执行所有先前添加的任务的方式:
ContinueUtility::closeConnection('Ready.');
ContinueUtility::executeAndClearTasks();