Laravel's middleware uses the decorator pattern. For example, verify maintenance mode, cookie encryption, open sessions, etc. Some of these processes are before the response, and some are after the response. The decorator mode is used to dynamically reduce or add functions, which greatly enhances the scalability of the framework.
#The following is a simple example of using the decorator pattern to maintain the Session implementation.
1. The decorator mode is not used and the module (WelcomeController::index method) needs to be modified.
class WelcomeController { public function index() { echo 'session start.', PHP_EOL; echo 'hello!', PHP_EOL; echo 'session close.', PHP_EOL; } }
2. Use the decorator mode, $pipeList represents the middleware array that needs to be executed. The key lies in the use of the array_reduce function.
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();
For more PHP related knowledge, please visit PHP Chinese website!
The above is the detailed content of php laravel request processing pipeline (decorator pattern). For more information, please follow other related articles on the PHP Chinese website!