Lumen 使用 dingo/api 的第一步便是 $app->register(Dingo\Api\Provider\LumenServiceProvider::class);,所以就从这个文件说起吧。

这个文件的父类是 \Dingo\Api\Provider\DingoServiceProvider,我们可以在这个文件中发现其注册了很多的东西到 App 容器里面,其中也有很多单例的对象等等等等,

但是,这些都不重要,重要的是 ::boot 方法里面的处理:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* Boot the service provider.
*
* @return void
*/
public function boot()
{
parent::boot();

// 1. 加载 dingo/api 配置
$this->app->configure('api');

// 2. 获取 app 容器反射对象
$reflection = new ReflectionClass($this->app);

// 3. 拿出 app 容器中定义的中间件, 传递进 \Dingo\Api\Http\Middleware\Request 中间件中
$this->app[Request::class]->mergeMiddlewares(
$this->gatherAppMiddleware($reflection)
);

// 4. 把 \Dingo\Api\Http\Middleware\Request 中间件加到 app 中间件处理链起始位置,
// 这样一来,请求会先经过 \Dingo\Api\Http\Middleware\Request 中间件处理,然后才是我们使用 `app()->middleware` 定义的中间件。
$this->addRequestMiddlewareToBeginning($reflection);

// Because Lumen sets the route resolver at a very weird point we're going to
// have to use reflection whenever the request instance is rebound to
// set the route resolver to get the current route.
$this->app->rebinding(IlluminateRequest::class, function ($app, $request) {
$request->setRouteResolver(function () use ($app) {
$reflection = new ReflectionClass($app);

$property = $reflection->getProperty('currentRoute');
$property->setAccessible(true);

return $property->getValue($app);
});
});

$this->app->routeMiddleware([
'api.auth' => Auth::class,
'api.throttle' => RateLimit::class,
'api.controllers' => PrepareController::class,
]);
}

到此为止,我们已经知道,我们的请求会先经过 \Dingo\Api\Http\Middleware\Request 中间件处理,这是很关键的一步,接下来,我们看看这个中间件做了什么:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
*/
public function handle($request, Closure $next)
{
try {
// 验证是否是 dingo 请求(前缀匹配上了 API_PREFIX 或者域名匹配上 API_DOMAIN),若不是会直接传递给下一个中间件
// (详情: \Dingo\Api\Provider\HttpServiceProvider::registerHttpValidation)
// 若是:
// 1. dingo 接管异常处理
// 2. 转换 \Illuminate\Http\Request 为 \Dingo\Api\Http\Request
// 3. 重新绑定 app 容器的 request 对象为 Dingo Request, 然后把 $request 传递给其他 app 容器中定义的中间件处理
// 4. 异常的时候返回异常响应对象
if ($this->validator->validateRequest($request)) {
$this->app->singleton(LaravelExceptionHandler::class, function ($app) {
return $app[ExceptionHandler::class];
});

$request = $this->app->make(RequestContract::class)->createFromIlluminate($request);

$this->events->fire(new RequestWasMatched($request, $this->app));

// 这个方法效果是所有中间件处理完之后才会执行控制器里面对应的方法
return $this->sendRequestThroughRouter($request);
}
} catch (Exception $exception) {
$this->exception->report($exception);

return $this->exception->handle($exception);
}

return $next($request);
}

最后一步,也是很关键的一步:

在所有中间件处理完之后,会把 $request 传递给 \Dingo\Api\Routing\Router::dispatch 处理,

处理完成后,使用 \Dingo\Api\Routing\Router::prepareResponse 处理控制器方法返回的响应结果

这是 dingo/api transformer include 操作实际执行的地方,

也许我们都曾经有过这样的疑惑:include 到底是在哪里进行数据库查询的? 其实是在这个方法里面执行的,具体细节有兴趣的执行研究。

这也算是 dingo 的一个特性了,但是 include 有太多坏处了,例如 N+1,但是也还是有解决方法的,不用 include... 还有嵌套 include 导致代码难以维护等等

原因: 项目重度依赖 Dingo, 直接放弃 Dingo 的代价太大

有兴趣了解原理的可以看 Dingo api 处理请求机制

各个依赖版本

  • laravel-s(3.5.8)

  • swoole 4.3.3

  • php-7.1.14

  • Lumen 5.5.38

  • Dingo/api 2.0.0-alpha2.2

步骤

修改 Laravel.php 的 handleDynamic 方法,如下

这一步需要另外 copy 一份 Laravel.php 出来,假设放在 App\Swoole\Laravel.php

App.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
... // 其他内容和原文件一致

public function handleDynamic(IlluminateRequest $request)
{
ob_start();

if ($this->isLumen()) {
// dingo router 路由处理
$response = app('Dingo\Api\Http\Middleware\Request')->handle($request, function ($request) {
return $request;
});

// 不是 dingo router 里面定义的路由
if ($response instanceof \Illuminate\Http\Request) {
$response = $this->app->dispatch($response);
}

if ($response instanceof SymfonyResponse) {
$content = $response->getContent();
} else {
$content = (string)$response;
}

if ($response instanceof \Symfony\Component\HttpFoundation\Response) {
$this->reflectionApp->callTerminableMiddleware($response);
}
} else {
$response = $this->kernel->handle($request);
$content = $response->getContent();
$this->kernel->terminate($request, $response);
}

// prefer content in response, secondly ob
if (!($response instanceof StreamedResponse) && strlen($content) === 0 && ob_get_length() > 0) {
$response->setContent(ob_get_contents());
}

ob_end_clean();

return $response;
}

... // 其他内容和原文件一致

原来的处理方式: $response = $this->app->dispatch($request); 这个处理方式会只使用 Lumen 的 app() 来处理 HTTP 请求,第一次请求正常,但是后续请求没什么意外是无法正常处理的。

新的处理方式: 使用 app('Dingo\Api\Http\Middleware\Request') 来处理 HTTP 请求,这是正常情况下 Dingo 处理请求的第一个经过的中间件,如果请求之后返回的还是一个 Request,而不是 Response,说明这不是使用 app('api.router') 定义的路由,退化为使用 $response = $this->app->dispatch($request); 处理该请求。

自动加载处理

然后在 bin/laravels.php $basePath 后面加上:

1
require_once $basePath . '/app/Swoole/Laravel.php';

目的: 自动加载机制在加载 Laravel 类的时候加载的是自定义的 Laravel.php,而不是原来的 Laravel.php 这样我们的修改就起效了。

Dingo 控制器在请求结束清理

添加文件 app/Cleaners/ControllerCleaner.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php

namespace App\Cleaners;

use Hhxsv5\LaravelS\Illuminate\Cleaners\CleanerInterface;
use Illuminate\Container\Container;

class ControllerCleaner implements CleanerInterface
{
public function clean(Container $app, Container $snapshot)
{
$ref = new \ReflectionObject($app);
$property = $ref->getProperty('instances');
$property->setAccessible(true);
$instances = $property->getValue($app);

foreach ($instances as $key => $instance) {
if ($instance instanceof \Laravel\Lumen\Routing\Controller) {
$instance = null;
app()->offsetUnset($key);
}
}
}
}

然后在 config/laravels.php 中的 cleaners 中加上该 Cleaner:

1
2
3
'cleaners' => [
App\Cleaners\ControllerCleaner::class, // 单例控制器清除
],

Dingo 中间件处理

新增文件 App.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php

namespace App\Cleaners;

use Dingo\Api\Http\Middleware\Request;
use Hhxsv5\LaravelS\Illuminate\Cleaners\CleanerInterface;
use Illuminate\Container\Container;

class MiddlewareCleaner implements CleanerInterface
{
public function clean(Container $app, Container $snapshot)
{
$reflect = new \ReflectionObject($snapshot);
$property = $reflect->getProperty('middleware');
$property->setAccessible(true);

$middleware = $property->getValue($snapshot);

// 移除 Dingo\Api\Http\Middleware\Request,防止死循环
$middleware = array_values(array_diff($middleware, [Request::class]));

app(Request::class)->setMiddlewares($middleware);
}
}

然后在 config/laravels.php 的 cleaners 中加上该 cleaner:

1
2
3
'cleaners' => [
App\Cleaners\MiddlewareCleaner::class, // 单例控制器清除
],

目的: 这个命名不是很准确地说明它的作用,其实这个文件的作用是把被 dingo 清除的中间件还原回来,这样后续的请求才会有第一次请求的中间件。

(dingo 会在其处理的周期内通过反射把 app 容器内的中间件清除,会导致后续请求没有经过这些中间件。)

这里说的中间件是定义在 app() App 容器中的中间件:

bootstrap/app.php

1
2
3
$app->middleware([
XxxMiddleware::class,
]);

php-fpm 环境下,由于每个请求相互之间不会相互影响,因此不会有问题,而在 laravel-s 环境下,请求结束之后,请求 context 不会被完全销毁,有可能会对后续请求造成影响。

依赖

项目路径

  • 根路径: /usr/local/share/openresty-docroot
  • 该目录下包含多个子目录,运行时的 document root 为其中的某一个目录,具体哪一个根据 HTTP 请求头 Accept 决定
  • 默认为 default 目录

nginx 配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
worker_processes  1;
error_log logs/error.log;
events {
worker_connections 1024;
}
http {
server {
listen 8081;
set $docroot "";
root /usr/local/share/openresty-docroot/$docroot/;
error_log "/var/log/nginx.log";

rewrite_by_lua_block {
ngx.var.docroot = 'default'
local accept = ngx.req.get_headers()["Accept"]

local version = string.gsub(accept, 'application/prs.gbcloud.', '')
version = string.gsub(version, '+json', '')
if (version ~= accept)
then
ngx.var.docroot = version
end
}
}
}

测试

  • 假设 /usr/local/share/openresty-docroot 下面有 defaultv1.2.3v1.2.4 三个目录,每个目录包含一个 index.html 文件,里面的内容分别是 defaultv1.2.3v1.2.4

目录结构

/usr/local/share/openresty-docroot ├── default │   └── index.html ├── v1.2.3 │   └── index.html └── v1.2.4 └── index.html

测试结果

  • 在 postman 里面不传递 Accept 头的时候,访问 http://localhost:8081 会得到 default
  • 传递 Accept: application/prs.gbcloud.v1.2.3+json 的时候,会得到 v1.2.3
  • 传递 Accept: application/prs.gbcloud.v1.2.4+json 的时候,会得到 v1.2.4

  • rsync 的时候 --include --exclude 不会使用绝对路径,全都是相对于 rsync 源目录的路径

  • --include 需要在 --exclude 前面

  • include 和 exclude 的路径前加 "/" 指的是相对 rsync 源目录路径的目录,如果不加,所有子目录下匹配上该路径的都会被匹配

  • 例子:

    • rsync /data/c --include="/e/" --exclude="e" root@127.0.0.1:/data/d,/data/c/d/e 会被同步, /data/c/e 不会被同步
    • rsync /data/c --exclude="e" root@127.0.0.1:/data/d, /data/c/d/e 和 /data/c/e 不会被同步,所有 /data/c 下目录名为 e 的都不会被同步(包括子目录下的)
    • rsync /data/c --include='/c/d/e/' --exclude="e" root@127.0.0.1:/data/d, /data/c/d/e 会被同步,所有 /data/c 下其他目录名为 e 的都不会被同步(包括子目录下的)
0%