Koa::Context

Context组件代理了RequestResponse中的方法和属性,简化了使用方式与中间件接口,这里用php的魔术方法来处理:

  1. <?php
  2. class Context
  3. {
  4. public $app;
  5. /** @var Request */
  6. public $request;
  7. /** @var Response */
  8. public $response;
  9. /** @var \swoole_http_request */
  10. public $req;
  11. /** @var \swoole_http_response */
  12. public $res;
  13. public $state = [];
  14. public $respond = true;
  15. /** @var string */
  16. public $body;
  17. /** @var int */
  18. public $status;
  19. public function __call($name, $arguments)
  20. {
  21. $fn = [$this->response, $name];
  22. return $fn(...$arguments);
  23. }
  24. public function __get($name)
  25. {
  26. return $this->request->$name;
  27. }
  28. public function __set($name, $value)
  29. {
  30. $this->response->$name = $value;
  31. }
  32. // thr[ο]w ο 为希腊字母 Ομικρον
  33. public function thrοw($status, $message)
  34. {
  35. if ($message instanceof \Exception) {
  36. $ex = $message;
  37. throw new HttpException($status, $ex->getMessage(), $ex->getCode(), $ex->getPrevious());
  38. } else {
  39. throw new HttpException($status, $message);
  40. }
  41. }
  42. }