Koa::Response

Response组件是对swoole_http_response的简单封装:

  1. <?php
  2. class Response
  3. {
  4. /* @var Application */
  5. public $app;
  6. /** @var \swoole_http_request */
  7. public $req;
  8. /** @var \swoole_http_response */
  9. public $res;
  10. /** @var Context */
  11. public $ctx;
  12. /** @var Request */
  13. public $request;
  14. public $isEnd = false;
  15. public function __construct(Application $app, Context $ctx,
  16. \swoole_http_request $req, \swoole_http_response $res)
  17. {
  18. $this->app = $app;
  19. $this->ctx = $ctx;
  20. $this->req = $req;
  21. $this->res = $res;
  22. }
  23. public function __call($name, $arguments)
  24. {
  25. /** @var $fn callable */
  26. $fn = [$this->res, $name];
  27. return $fn(...$arguments);
  28. }
  29. public function __get($name)
  30. {
  31. return $this->res->$name;
  32. }
  33. public function __set($name, $value)
  34. {
  35. switch ($name) {
  36. case "type":
  37. return $this->res->header("Content-Type", $value);
  38. case "lastModified":
  39. return $this->res->header("Last-Modified", $value);
  40. case "etag":
  41. return $this->res->header("ETag", $value);
  42. case "length":
  43. return $this->res->header("Content-Length", $value);
  44. default:
  45. return $this->res->header($name, $value);
  46. }
  47. }
  48. public function end($html = "")
  49. {
  50. if ($this->isEnd) {
  51. return false;
  52. }
  53. $this->isEnd = true;
  54. return $this->res->end($html);
  55. }
  56. public function redirect($url, $status = 302)
  57. {
  58. $this->res->header("Location", $url);
  59. $this->res->header("Content-Type", "text/plain; charset=utf-8");
  60. $this->ctx->status = $status;
  61. $this->ctx->body = "Redirecting to $url.";
  62. }
  63. public function render($file)
  64. {
  65. $this->ctx->body = (yield Template::render($file, $this->ctx->state));
  66. }
  67. }