controllers.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. use Demo\User;
  3. use Silex\Application;
  4. use Symfony\Component\HttpFoundation\Request;
  5. use Symfony\Component\HttpFoundation\Response;
  6. //Request::setTrustedProxies(array('127.0.0.1'));
  7. $app->get('/', function () use ($app) {
  8. return $app['twig']->render('index.html.twig', []);
  9. })
  10. ->bind('homepage');
  11. $blogPosts = [
  12. 1 => [
  13. 'date' => '2011-03-29',
  14. 'author' => 'igorw',
  15. 'title' => 'Using Silex',
  16. 'body' => '...It takes time on version changes...',
  17. ],
  18. ];
  19. // Available automatic arguments on controllers: Application, Request.
  20. $app->get('/blog', function () use ($blogPosts) {
  21. $output = '';
  22. foreach ($blogPosts as $post) {
  23. $output .= $post ['title'];
  24. $output .= '<br />';
  25. }
  26. return $output;
  27. });
  28. $app->get('/blog/{id}', function (Application $app, $id) use ($blogPosts) {
  29. if (!isset ($blogPosts [$id])) {
  30. $app->abort(Response::HTTP_NOT_FOUND, "Post $id does not exist.");
  31. }
  32. $post = $blogPosts [$id];
  33. return "<h1> {$post['title']}</h1>" . "<p> {$post['body']} </p>";
  34. });
  35. $app->post('/feedback', function (Application $app, Request $request) {
  36. $message = $request->get('message');
  37. mail($app['app.mail_to'], '[YourSite] Feedback', $message);
  38. return new Response ('Thank you for your feedback!', Response::HTTP_CREATED);
  39. });
  40. $app->get('/user/{user}', function (User $user) {
  41. return "<h1>User {$user->getId()}</h1>\n";
  42. })->convert ('user', 'converter.user:convert');
  43. $app->error(function (\Exception $e, Request $request, $code) use ($app) {
  44. if ($app['debug']) {
  45. return;
  46. }
  47. // 404.html, or 40x.html, or 4xx.html, or error.html
  48. $templates = array(
  49. 'errors/'.$code.'.html.twig',
  50. 'errors/'.substr($code, 0, 2).'x.html.twig',
  51. 'errors/'.substr($code, 0, 1).'xx.html.twig',
  52. 'errors/default.html.twig',
  53. );
  54. return new Response($app['twig']->resolveTemplate($templates)->render(array('code' => $code)), $code);
  55. });