controllers.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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>Fifi: {$post['title']}</h1>" . "<p> {$post['body']} </p>";
  34. })->assert('id', '\d+')
  35. ->when("request.headers.get('User-Agent') matches '/firefox/i'");
  36. $app->get('/blog/{id}', function (Application $app, $id) use ($blogPosts) {
  37. if (!isset ($blogPosts [$id])) {
  38. $app->abort(Response::HTTP_NOT_FOUND, "Post $id does not exist.");
  39. }
  40. $post = $blogPosts [$id];
  41. return "<h1> {$post['title']}</h1>" . "<p> {$post['body']} </p>";
  42. })->assert('id', '\d+');
  43. $app->post('/feedback', function (Application $app, Request $request) {
  44. $message = $request->get('message');
  45. mail($app['app.mail_to'], '[YourSite] Feedback', $message);
  46. return new Response ('Thank you for your feedback!', Response::HTTP_CREATED);
  47. });
  48. $app->get('/user/{user}', function (User $user) {
  49. return "<h1>User {$user->getId()}</h1>\n";
  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 = array(
  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)->render(array('code' => $code)), $code);
  63. });