slim3 middleware解析

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

<?php


require 'vendor/autoload.php';

$app = new Slim\App();

// 第一種方式(應(yīng)用級中間件)
$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請求進來時也是從外層到里層再到外層。應(yīng)用級中間件先執(zhí)行瓮具,執(zhí)行到$route->run()時荧飞,會繼續(xù)執(zhí)行路由級中間件


image.png

所以訪問http://127.0.0.1:8000/hello/fdas,結(jié)果是

BEFORE middle2
BEFORE middle1
Hello, fdas
AFTER middle1
AFTER middle2

接著我們來瞅瞅源碼的實現(xiàn)名党,首先我們先看第一種方式是如何添加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耳幢,然后將一個閉包函數(shù)賦值給$this->tip。在這個函數(shù)中欧啤,call_user_func($callable, $request, $response, $next)就是調(diào)用我們middleware中的__invoke方法睛藻。

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

/**
 *  第一次添加middleware (應(yīng)用級)
 */  
$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對象
             }

這樣當(dāng)我們執(zhí)行request時(可以看我的另一篇文章關(guān)于request的)邢隧,即執(zhí)行$this->tip(),

  • 1店印、先走HMiddleWare的__invoke方法,輸出brfore后執(zhí)行next()
  • 2府框、next()就是$app->__invoke()方法吱窝,在里面執(zhí)行$route->run()
  • 3、在$route->run()添加了路由中間后在執(zhí)行迫靖,先執(zhí)行callable,輸出brfore后院峡,然后在執(zhí)行next(),
  • 4系宜、next()就是route->__invoke(), 執(zhí)行完后調(diào)用callable的after照激, 在調(diào)用HMiddleWare中的after
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市盹牧,隨后出現(xiàn)的幾起案子俩垃,更是在濱河造成了極大的恐慌,老刑警劉巖汰寓,帶你破解...
    沈念sama閱讀 221,695評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件口柳,死亡現(xiàn)場離奇詭異,居然都是意外死亡有滑,警方通過查閱死者的電腦和手機跃闹,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,569評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人望艺,你說我怎么就攤上這事苛秕。” “怎么了找默?”我有些...
    開封第一講書人閱讀 168,130評論 0 360
  • 文/不壞的土叔 我叫張陵艇劫,是天一觀的道長。 經(jīng)常有香客問我惩激,道長店煞,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,648評論 1 297
  • 正文 為了忘掉前任咧欣,我火速辦了婚禮浅缸,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘魄咕。我一直安慰自己衩椒,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 68,655評論 6 397
  • 文/花漫 我一把揭開白布哮兰。 她就那樣靜靜地躺著毛萌,像睡著了一般。 火紅的嫁衣襯著肌膚如雪喝滞。 梳的紋絲不亂的頭發(fā)上阁将,一...
    開封第一講書人閱讀 52,268評論 1 309
  • 那天,我揣著相機與錄音右遭,去河邊找鬼做盅。 笑死,一個胖子當(dāng)著我的面吹牛窘哈,可吹牛的內(nèi)容都是我干的吹榴。 我是一名探鬼主播,決...
    沈念sama閱讀 40,835評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼滚婉,長吁一口氣:“原來是場噩夢啊……” “哼图筹!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起让腹,我...
    開封第一講書人閱讀 39,740評論 0 276
  • 序言:老撾萬榮一對情侶失蹤远剩,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后骇窍,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體瓜晤,經(jīng)...
    沈念sama閱讀 46,286評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,375評論 3 340
  • 正文 我和宋清朗相戀三年腹纳,在試婚紗的時候發(fā)現(xiàn)自己被綠了痢掠。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片哈恰。...
    茶點故事閱讀 40,505評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖志群,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情蛔钙,我是刑警寧澤锌云,帶...
    沈念sama閱讀 36,185評論 5 350
  • 正文 年R本政府宣布,位于F島的核電站吁脱,受9級特大地震影響桑涎,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜兼贡,卻給世界環(huán)境...
    茶點故事閱讀 41,873評論 3 333
  • 文/蒙蒙 一攻冷、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧遍希,春花似錦等曼、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,357評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至废封,卻和暖如春州泊,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背漂洋。 一陣腳步聲響...
    開封第一講書人閱讀 33,466評論 1 272
  • 我被黑心中介騙來泰國打工遥皂, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人刽漂。 一個月前我還...
    沈念sama閱讀 48,921評論 3 376
  • 正文 我出身青樓演训,卻偏偏與公主長得像,于是被迫代替她去往敵國和親爽冕。 傳聞我的和親對象是個殘疾皇子仇祭,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,515評論 2 359

推薦閱讀更多精彩內(nèi)容