好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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函数。

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相关知识,请访问PHP中文网!

以上就是php laravel请求处理管道(装饰者模式)的详细内容,更多请关注Gxlcms其它相关文章!

查看更多关于php laravel请求处理管道(装饰者模式)的详细内容...

  阅读:51次