slim3 middleware解析

slim3中的middleware有兩種方式添加:

<?php


require 'vendor/autoload.php';

$app = new Slim\App();

// 第一種方式(應用級中間件)
$app->add(new HMiddleWare());

// 第二種方式 (路由中間件)
$app->get('/hello/{name}', function ($request, $response, $args) {
    return $response->getBody()->write("Hello, " . $args['name']);
})->add(function($request, $response, $next) {
    $response->getBody()->write('BEFORE middle1');
    $response = $next($request, $response);
    $response->getBody()->write('AFTER middle1');

    return $response;
});

$app->run();


class HMiddleWare
{
    function __invoke($request, $response, $next)
    {
        $response->getBody()->write('BEFORE middle2');
        $response = $next($request, $response);
        $response->getBody()->write('AFTER middle2');

        return $response;
    }
}\

slim添加中間件時會一層一層的套,先添加的在最里面,后添加的在最外面,這樣request請求進來時也是從外層到里層再到外層。應用級中間件先執行,執行到$route->run()時,會繼續執行路由級中間件


image.png

所以訪問http://127.0.0.1:8000/hello/fdas,結果是

BEFORE middle2
BEFORE middle1
Hello, fdas
AFTER middle1
AFTER middle2

接著我們來瞅瞅源碼的實現,首先我們先看第一種方式是如何添加middleware,

public function add($callable)
{
    return $this->addMiddleware(new DeferredCallable($callable, $this->container));
}

protected function addMiddleware(callable $callable)
{
    if ($this->middlewareLock) {
        throw new RuntimeException('Middleware can’t be added once the stack is dequeuing');
    }
    
    // 第一次將app對象賦值給$this->tip
    if (is_null($this->tip)) {
        $this->seedMiddlewareStack();
    }
    $next = $this->tip;
    $this->tip = function (
        ServerRequestInterface $request,
        ResponseInterface $response
    ) use (
        $callable,
        $next
    ) {
        $result = call_user_func($callable, $request, $response, $next);
        if ($result instanceof ResponseInterface === false) {
            throw new UnexpectedValueException(
                'Middleware must return instance of \Psr\Http\Message\ResponseInterface'
            );
        }

        return $result;
    };

    return $this;
}

protected function seedMiddlewareStack(callable $kernel = null)
{
    if (!is_null($this->tip)) {
        throw new RuntimeException('MiddlewareStack can only be seeded once.');
    }
    if ($kernel === null) {
        $kernel = $this;
    }
    $this->tip = $kernel;
}

先判斷$this->tip是否為null,即第一次將app對象賦值給$this->tip,然后將$this->tip賦值給$next,然后將一個閉包函數賦值給$this->tip。在這個函數中,call_user_func($callable, $request, $response, $next)就是調用我們middleware中的__invoke方法。

我們結合上面的例子來講一講,在我$app->add(new HMiddleWare())時

/**
 *  第一次添加middleware (應用級)
 */  
$callable      =>     HMiddleWare對象
$this->tip     =>     app對象
$next          =>     app對象
$this->tip     =>     function($request, $response) use (HMiddleWare對象,  app對象) {
    $result = call_user_func(HMiddleWare對象, $request, $response,  app對象);
}


/**
 *  第二次添加middleware (路由級)
 */
$callable         =>    function($request, $response, $next) {
    $response->getBody()->write('BEFORE middle1');
    $response = $next($request, $response);
    $response->getBody()->write('AFTER middle1');
    return $response;
}
$this->tip        =>    route對象
$next             =>    route對象
$this->tip        =>    function($request, $response) use ($callable,  route對象) {
    $result = call_user_func(
                          function($request, $response, $next) {
                                     $response->getBody()->write('BEFORE middle1');
                                     $response = $next($request, $response);
                                     $response->getBody()->write('AFTER middle1');
                                    return $response;
                          },
                         $request,
                         $response,  
                         route對象
             }

這樣當我們執行request時(可以看我的另一篇文章關于request的),即執行$this->tip(),

  • 1、先走HMiddleWare的__invoke方法,輸出brfore后執行next()
  • 2、next()就是$app->__invoke()方法,在里面執行$route->run()
  • 3、在$route->run()添加了路由中間后在執行,先執行callable,輸出brfore后,然后在執行next(),
  • 4、next()就是route->__invoke(), 執行完后調用callable的after, 在調用HMiddleWare中的after
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容