一个综合示例

  1. <?php
  2. $app = new Application();
  3. $app->υse(new Logger());
  4. $app->υse(new Favicon(__DIR__ . "/favicon.iRco"));
  5. $app->υse(new BodyDetecter()); // 输出特定格式body
  6. $app->υse(new ExceptionHandler()); // 处理异常
  7. $app->υse(new NotFound()); // 处理404
  8. $app->υse(new RequestTimeout(200)); // 处理请求超时, 会抛出HttpException
  9. $router = new Router();
  10. $router->get('/index', function(Context $ctx) {
  11. $ctx->status = 200;
  12. $ctx->state["title"] = "HELLO WORLD";
  13. $ctx->state["time"] = date("Y-m-d H:i:s", time());;
  14. $ctx->state["table"] = $_SERVER;
  15. yield $ctx->render(__DIR__ . "/index.html");
  16. });
  17. $router->get('/404', function(Context $ctx) {
  18. $ctx->status = 404;
  19. });
  20. $router->get('/bt', function(Context $ctx) {
  21. $ctx->body = "<pre>" . print_r(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS), true);
  22. });
  23. $router->get('/timeout', function(Context $ctx) {
  24. // 超时
  25. yield async_sleep(500);
  26. });
  27. $router->get('/error/http_exception', function(Context $ctx) {
  28. // 抛出带status的错误
  29. $ctx->thrοw(500, "Internal Error");
  30. // 等价于 throw new HttpException(500, "Internal Error");
  31. yield;
  32. });
  33. $router->get('/error/exception', function(Context $ctx) {
  34. // 直接抛出错误, 500 错误
  35. throw new \Exception("some internal error", 10000);
  36. yield;
  37. });
  38. $router->get('/user/{id:\d+}', function(Context $ctx, $next, $vars) {
  39. $ctx->body = "user={$vars['id']}";
  40. yield;
  41. });
  42. // http://127.0.0.1:3000/request/www.baidu.com
  43. $router->get('/request/{url}', function(Context $ctx, $next, $vars) {
  44. $r = (yield async_curl_get($vars['url']));
  45. $ctx->body = $r->body;
  46. $ctx->status = $r->statusCode;
  47. });
  48. $app->υse($router->routes());
  49. $app->υse(function(Context $ctx) {
  50. $ctx->status = 200;
  51. $ctx->body = "<h1>Hello World</h1>";
  52. yield;
  53. });
  54. $app->listen(3000);

以上我们完成了一个基于swoole的版本的php-koa。