21,886
社区成员
发帖
与我相关
我的任务
分享
<?php
// 实例1
class test{
public function run($index)
{
echo 'start:'.$index."<br />";
sleep(3);
echo 'end:'.$index."<br />";
}
}
$test = new test();
$test->run(1);
$test->run(2);
class Test{
public static $jobs=[];
public function add($index){
static::$jobs[] = $index;
echo 'start:'.$index."<br />";
}
public function run(){
foreach (static::$jobs as $index) {
echo 'end:'.$index."<br />";
}
}
}
$test = new Test;
$test->add(1);
$test->add(2);
$test->run();
interface Event{
public function handle();
}
class Job implements Event{
public $param;
public function __construct($param){
$this->param = $param;
}
public function handle(){
echo 'end:'.$this->param."<br />";
}
}
class Test{
public static $jobs=[];
public function run(Event $job){
static::$jobs[] = $job;
echo 'start:'.$job->param."<br />";
}
public function __destruct(){
foreach (static::$jobs as $job) {
$job->handle();
}
}
}
$test = new Test;
$test->run( new Job(1) );
$test->run( new Job(2) );
interface Event{
public function handle(Closure $next);
}
class Job implements Event{
public $param;
public function __construct($param){
$this->param = $param;
}
public function handle(Closure $next){
echo 'start:'.$this->param."<br />";
$next();
}
public function boot(){
echo 'end:'.$this->param."<br />";
}
}
class Test{
public $jobs=[];
public function __construct(array $arr){
foreach ($arr as $v) {
$this->jobs[] = new Job($v);
}
}
public function run(){
$pipes=array_reverse($this->jobs);
$firstSlice=function(){
foreach ($this->jobs as $job) {
echo $job->boot();
}
};
call_user_func(
array_reduce($pipes,$this->getSlice(),$firstSlice)
);
}
function getSlice(){
return function ($stack,$pipe){
return function () use ($stack,$pipe){
return $pipe->handle($stack);
};
};
}
}
$arr = [1,2];
$test = new Test($arr);
$test->run( );