controllers.php 2.4 KB

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