接下来我们来看Koa的仅有四个组件,Application Context Request Response 依次给予实现:

Koa-guide


Koa::Application

The application object is Koa’s interface with node’s http server and handles the registration

of middleware, dispatching to the middleware from http, default error handling, as well as

configuration of the context, request and response objects.

我们的App模块是对swoole_http_server的简单封装,在onRequest回调中对中间件compose并执行:

  1. <?php
  2. class Application
  3. {
  4. /** @var \swoole_http_server */
  5. public $httpServer;
  6. /** @var Context Prototype Context */
  7. public $context;
  8. public $middleware = [];
  9. public $fn;
  10. public function __construct()
  11. {
  12. // 我们构造一个Context原型
  13. $this->context = new Context();
  14. $this->context->app = $this;
  15. }
  16. // 我们用υse方法添加符合接口的中间件
  17. // middleware :: (Context $ctx, $next) -> void
  18. public function υse(callable $fn)
  19. {
  20. $this->middleware[] = $fn;
  21. return $this;
  22. }
  23. // compose中间件 监听端口提供服务
  24. public function listen($port = 8000, array $config = [])
  25. {
  26. $this->fn = compose($this->middleware);
  27. $config = ['port' => $port] + $config + $this->defaultConfig();
  28. $this->httpServer = new \swoole_http_server($config['host'], $config['port'], SWOOLE_PROCESS, SWOOLE_SOCK_TCP);
  29. $this->httpServer->set($config);
  30. // 省略绑定 swoole HttpServer 事件, start shutdown connect close workerStart workerStop workerError request
  31. // ...
  32. $this->httpServer->start();
  33. }
  34. public function onRequest(\swoole_http_request $req, \swoole_http_response $res)
  35. {
  36. $ctx = $this->createContext($req, $res);
  37. $reqHandler = $this->makeRequestHandler($ctx);
  38. $resHandler = $this->makeResponseHandler($ctx);
  39. spawn($reqHandler, $resHandler);
  40. }
  41. protected function makeRequestHandler(Context $ctx)
  42. {
  43. return function() use($ctx) {
  44. yield setCtx("ctx", $ctx);
  45. $ctx->res->status(404);
  46. $fn = $this->fn;
  47. yield $fn($ctx);
  48. };
  49. }
  50. protected function makeResponseHandler(Context $ctx)
  51. {
  52. return function($r = null, \Exception $ex = null) use($ctx) {
  53. if ($ex) {
  54. $this->handleError($ctx, $ex);
  55. } else {
  56. $this->respond($ctx);
  57. }
  58. };
  59. }
  60. protected function handleError(Context $ctx, \Exception $ex = null)
  61. {
  62. if ($ex === null) {
  63. return;
  64. }
  65. if ($ex && $ex->getCode() !== 404) {
  66. sys_error($ctx);
  67. sys_error($ex);
  68. }
  69. // 非 Http异常, 统一500 status,对外显示异常code
  70. // Http 异常,自定义status,自定义是否暴露Msg
  71. $msg = $ex->getCode();
  72. if ($ex instanceof HttpException) {
  73. $status = $ex->status ?: 500;
  74. $ctx->res->status($status);
  75. if ($ex->expose) {
  76. $msg = $ex->getMessage();
  77. }
  78. } else {
  79. $ctx->res->status(500);
  80. }
  81. // force text/plain
  82. $ctx->res->header("Content-Type", "text"); // TODO accepts
  83. $ctx->res->write($msg);
  84. $ctx->res->end();
  85. }
  86. protected function respond(Context $ctx)
  87. {
  88. if ($ctx->respond === false) return; // allow bypassing Koa
  89. $body = $ctx->body;
  90. $code = $ctx->status;
  91. if ($code !== null) {
  92. $ctx->res->status($code);
  93. }
  94. // status.empty() $ctx->body = null; res->end()
  95. if ($body !== null) {
  96. $ctx->res->write($body);
  97. }
  98. $ctx->res->end();
  99. }
  100. protected function createContext(\swoole_http_request $req, \swoole_http_response $res)
  101. {
  102. // 可以在Context挂其他组件 $app->foo = bar; $app->listen();
  103. $context = clone $this->context;
  104. $request = $context->request = new Request($this, $context, $req, $res);
  105. $response = $context->response = new Response($this, $context, $req, $res);
  106. $context->app = $this;
  107. $context->req = $req;
  108. $context->res = $res;
  109. $request->response = $response;
  110. $response->request = $request;
  111. $request->originalUrl = $req->server["request_uri"];
  112. $request->ip = $req->server["remote_addr"];
  113. return $context;
  114. }
  115. }