laravel的中間件使用了裝飾者模式。好比,驗證維護模式,cookie加密,開啓會話等等。這些處理有些在響應前,有些在響應以後,使用裝飾者模式動態減小或增長功能,使得框架可擴展性大大加強。
接下來簡單舉個例子,使用裝飾者模式實現維護Session實現。
沒有使用裝飾者模式,須要對模塊(WelcomeController::index方法)進行修改。
class WelcomeController
{
public function index()
{
echo 'session start.', PHP_EOL;
echo 'hello!', PHP_EOL;
echo 'session close.', PHP_EOL;
}
}
使用裝飾者模式,$pipeList表示須要執行的中間件數組。關鍵在於使用了array_reduce函數(http://php.net/manual/zh/function.array-reduce.php)
class WelcomeController
{
public function index()
{
echo 'hello!', PHP_EOL;
}
}
interface Middleware
{
public function handle(Closure $next);
}
class Seesion implements Middleware
{
public function handle(Closure $next)
{
echo 'session start.', PHP_EOL;
$next();
echo 'session close.', PHP_EOL;
}
}
$pipeList = [
"Seesion",
];
function _go($step, $className)
{
return function () use ($step, $className) {
$o = new $className();
return $o->handle($step);
};
}
$go = array_reduce($pipeList, '_go', function () {
return call_user_func([new WelcomeController(), 'index']);
});
$go();
php