php幾年前已經採用nodejs管理應用依賴包的方法(npm/borwser),產生了composer;如今,api接口開放時代,php的微型框架slim爲api而生,它集成psr/全名空間/中間件的方式,這種由python django(https://docs.djangoproject.com/en/1.6/topics/http/middleware/)流行而來的處理方式已經被其它框架所接受,好比nodejs的koa。php
如今slim已經進行到3.0,每一個版本的更新都很激進,幾乎面目全非。html
slim3中關於中間件的說明是這樣的:node
http://www.slimframework.com/docs/concepts/middleware.htmlpython
能夠看出,請求經過入口,經層層的中間處理,好比過濾、認證、加載數據庫、加載緩存。。。最後到達app核心層,而後response又經原路返回,最後輸出。es6
每一個middleware都是一個匿名函數,函數處理完畢,最後返回一個對下一中間件的調用;若是沒有調用,那麼中斷對其他中間的處理,直接到達核心的app,輸出結果。數據庫
<?php
class ExampleMiddleware
{
/**
* Example middleware invokable class
*
* @param \Psr\Http\Message\ServerRequestInterface $request PSR7 request
* @param \Psr\Http\Message\ResponseInterface $response PSR7 response
* @param callable $next Next middleware
*
* @return \Psr\Http\Message\ResponseInterface
*/
public function __invoke($request, $response, $next)
{
$response->getBody()->write('BEFORE');
$response = $next($request, $response);
$response->getBody()->write('AFTER'); npmreturn $response;
}
}django
nodejs中,koa框架也是這個原理:api
http://koa.rednode.cn/#introduction緩存
不一樣的是,nodejs經過es6的generator關鍵字yield來傳遞到下一中間件的:
var koa = require('koa');
var app = koa();// x-response-time
app.use(function *(next){
var start = new Date;
yield next;
var ms = new Date - start;
this.set('X-Response-Time', ms + 'ms');
});// logger
app.use(function *(next){
var start = new Date;
yield next;
var ms = new Date - start;
console.log('%s %s - %s', this.method, this.url, ms);
});// response
app.use(function *(){
this.body = 'Hello World';
});app.listen(3000);
.middleware1 {
// (1) do some stuff
.middleware2 {
// (2) do some other stuff
.middleware3 {
// (3) NO next yield !
// this.body = 'hello world'
}
// (4) do some other stuff later
}
// (5) do some stuff lastest and return
}
-- end --