1

装饰者模式在中间件中使用

后盾网

<?php

namespace App;

interface Middleware
{
    public function handle($next);
}

class Session implements Middleware
{
    public function handle($next)
    {
        echo "<br/>Session Start<br/>";
        $next();
        echo "<br/>Session End<br/>";
    }
}

class Mysql implements Middleware
{
    public function handle($next)
    {
        echo "<br/>Mysql Start<br/>";
        $next();
        echo "<br/>Mysql end<br/>";
    }
}

function run($next, $step)
{
    return function () use ($next, $step) {
        call_user_func_array([new $step, 'handle'], [$next]);
    };
}

$class    = [Session::class, Mysql::class];
$callback = array_reduce($class, 'App\run', function () {
});
$callback();

运行结果

Mysql Start

Session Start

Session End

Mysql end

后盾网向军
26 声望6 粉丝

HDPHP&HDCMS作者