controllers.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. //Request::setTrustedProxies(array('127.0.0.1'));
  9. $app->get('/', function () use ($app) {
  10. return $app['twig']->render('index.html.twig', []);
  11. })->bind('homepage');
  12. $blogPosts = [
  13. 1 => [
  14. 'date' => '2011-03-29',
  15. 'author' => 'igorw',
  16. 'title' => 'Using Silex',
  17. 'body' => '...It takes time on version changes...',
  18. ],
  19. 2 => [
  20. 'date' => '2015-03-29',
  21. 'author' => 'igorw',
  22. 'title' => 'Using Silex 2',
  23. 'body' => '...Especialy S1 to S2...',
  24. ],
  25. ];
  26. // Available automatic arguments on controllers: Application, Request.
  27. $app->get('/blogs', function () use ($blogPosts) {
  28. $output = "<ul>\n";
  29. foreach ($blogPosts as $post) {
  30. $output .= "<li>" . $post ['title'] . "</li>\n";
  31. }
  32. $output .= "</ul>\n";
  33. return $output;
  34. });
  35. // Default: http://blog, not http://blog/
  36. $app->get('/blog/{id}', BlogController::class . '::fifiAction')
  37. ->assert('id', '\d+')
  38. ->when("request.headers.get('User-Agent') matches '/firefox/i'");
  39. $app->get('/blog/{id}', function (Application $app, $id) use ($blogPosts) {
  40. if (!isset ($blogPosts [$id])) {
  41. $app->abort(Response::HTTP_NOT_FOUND, "Post $id does not exist.");
  42. }
  43. $post = $blogPosts [$id];
  44. return "<h1> {$post['title']}</h1>" . "<p> {$post['body']} </p>";
  45. })->assert('id', '\d+')
  46. ->value('id', 1)
  47. ->bind('blog_post');
  48. $app->post('/feedback', FeedbackController::class . '::feedbackAction');
  49. $app->get('/user/{user}', UserController::class . '::itemAction')
  50. ->convert('user', 'converter.user:convert');
  51. $app->error(function (\Exception $e, Request $request, $code) use ($app) {
  52. if ($app['debug']) {
  53. return;
  54. }
  55. // 404.html, or 40x.html, or 4xx.html, or error.html
  56. $templates = [
  57. 'errors/' . $code . '.html.twig',
  58. 'errors/' . substr($code, 0, 2) . 'x.html.twig',
  59. 'errors/' . substr($code, 0, 1) . 'xx.html.twig',
  60. 'errors/default.html.twig',
  61. ];
  62. return new Response($app['twig']->resolveTemplate($templates)
  63. ->render(['code' => $code]), $code);
  64. });