Home > Backend Development > PHP Tutorial > php laravel request processing pipeline (decorator pattern)

php laravel request processing pipeline (decorator pattern)

angryTom
Release: 2023-04-07 20:46:02
forward
3412 people have browsed it

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.

php laravel request processing pipeline (decorator pattern)

#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;
    }
}
Copy after login

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();
Copy after login

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!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template