controllers.php 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. <?php
  2. use demo\Controllers\BlogController;
  3. use demo\Controllers\FeedbackController;
  4. use demo\Controllers\UserController;
  5. use Silex\Application;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\HttpKernel\Exception\HttpException;
  9. //Request::setTrustedProxies(array('127.0.0.1'));
  10. // Fixed parameters for after() global middleware.
  11. $afterAllMiddleware = function (Request $request, Response $response, Application $app) {
  12. echo "<p>In aAM</p>\n";
  13. };
  14. $beforeAllMiddleware = function (Request $request, Application $app) {
  15. echo "<p>In bAM</p>\n";
  16. };
  17. // This type of global configuration does not apply to mounted controllers,
  18. // which have their own "global" configuration.
  19. $app->before($beforeAllMiddleware);
  20. $app->after($afterAllMiddleware);
  21. $app->get('/', function () use ($app) {
  22. return $app['twig']->render('index.html.twig', []);
  23. })->bind('homepage');
  24. $blogPosts = [
  25. 1 => [
  26. 'date' => '2011-03-29',
  27. 'author' => 'igorw',
  28. 'title' => 'Using Silex',
  29. 'body' => '...It takes time on version changes...',
  30. ],
  31. 2 => [
  32. 'date' => '2015-03-29',
  33. 'author' => 'igorw',
  34. 'title' => 'Using Silex 2',
  35. 'body' => '...Especialy S1 to S2...',
  36. ],
  37. ];
  38. // Available automatic arguments on controllers: Application, Request.
  39. $app->get('/blogs', function () use ($blogPosts) {
  40. $output = "<ul>\n";
  41. foreach ($blogPosts as $post) {
  42. $output .= "<li>" . $post ['title'] . "</li>\n";
  43. }
  44. $output .= "</ul>\n";
  45. return $output;
  46. })->bind('blog_list');
  47. $app->get('/blogs-json-view', function () use ($blogPosts) {
  48. return $blogPosts; // Rely on the view handler.
  49. });
  50. // Default: http://blog, not http://blog/
  51. $app->get('/blog/{id}', BlogController::class . '::fifiAction')
  52. ->assert('id', '\d+')
  53. ->when("request.headers.get('User-Agent') matches '/firefox/i'");
  54. $app->get('/blog/{id}', function (Application $app, $id) use ($blogPosts) {
  55. if (!isset ($blogPosts [$id])) {
  56. // Will trigger the error() (or built-in) error handler.1
  57. $app->abort(Response::HTTP_NOT_FOUND, "Post $id does not exist.");
  58. }
  59. $post = $blogPosts [$id];
  60. return "<h1> {$post['title']}</h1>" . "<p> {$post['body']} </p>";
  61. })->assert('id', '\d+')
  62. ->value('id', 1)
  63. ->bind('blog_post');
  64. $app->post('/feedback', FeedbackController::class . '::feedbackAction');
  65. $app->get('/user/{user}', UserController::class . '::itemAction')
  66. ->convert('user', 'converter.user:convert');
  67. // Register a view handler. They can also receive Request $request as 2nd arg,
  68. // e.g. for basic content negotiation.
  69. $app->view(function (array $controllerResult) use ($app) {
  70. return $app->json($controllerResult);
  71. });
  72. // Handlers are examined in order, and called in a chain with the result of the
  73. // previous one. The last one must return a string or Response.
  74. /* Error handlers receive exactly these arguments, in that order. */
  75. $app->error(function (HttpException $e, Request $request, $code) {
  76. $response = new Response('HTTP Error caught: skipping generic error handler.',
  77. // This status is ignored by Silex, which tries to ensure status code
  78. // consistency with the exception.
  79. Response::HTTP_NOT_FOUND,
  80. // But we can force it with this fake header, which is removed before
  81. // sending the response to the user agent.
  82. ['X-Status-Code' => Response::HTTP_OK]);
  83. return $response;
  84. });
  85. /* Custom error handlers registered with error() take precedence over the
  86. built-in error handler provider by Silex, but the formatted error messages it
  87. provides can be accessed in debug mode by returning based on $app['debug']
  88. like this.
  89. */
  90. $app->error(function (\Exception $e, Request $request, $code) use ($app) {
  91. // Use the default handler in debug mode.
  92. if ($app['debug']) {
  93. return;
  94. }
  95. // Use our error formats otherwise.
  96. // 404.html, or 40x.html, or 4xx.html, or error.html
  97. $templates = [
  98. 'errors/' . $code . '.html.twig',
  99. 'errors/' . substr($code, 0, 2) . 'x.html.twig',
  100. 'errors/' . substr($code, 0, 1) . 'xx.html.twig',
  101. 'errors/default.html.twig',
  102. ];
  103. return new Response($app['twig']->resolveTemplate($templates)
  104. ->render(['code' => $code]), $code);
  105. });