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();
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/105942.html
標籤:PHP
上一篇:Jsonp跨域原理及簡單應用
