天天看點

php laravel請求處理管道(裝飾者模式)

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)

    interface Middleware

        public function handle(Closure $next);

    class Seesion implements Middleware

        public function handle(Closure $next)

            $next();

    $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();

繼續閱讀