BlogController.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. namespace demo\Controllers;
  3. use Silex\Application;
  4. use Symfony\Component\HttpFoundation\Response;
  5. /**
  6. * Class BlogController demonstrates most basic controller types.
  7. *
  8. * Available automatic arguments on controllers: Application, Request.
  9. *
  10. * @package demo\Controllers
  11. */
  12. class BlogController {
  13. const POSTS = [
  14. 1 => [
  15. 'date' => '2011-03-29',
  16. 'author' => 'igorw',
  17. 'title' => 'Using Silex',
  18. 'body' => '...It takes time on version changes...',
  19. ],
  20. 2 => [
  21. 'date' => '2015-03-29',
  22. 'author' => 'igorw',
  23. 'title' => 'Using Silex 2',
  24. 'body' => '...Especialy S1 to S2...',
  25. ],
  26. ];
  27. // Default: http://blog, not http://blog/
  28. public function fifiAction(Application $app, $id) {
  29. return "<h1>Fifi action {$id} </h1>\n";
  30. }
  31. public function index() {
  32. $output = "<ul>\n";
  33. foreach (static::POSTS as $post) {
  34. $output .= "<li>" . $post ['title'] . "</li>\n";
  35. }
  36. $output .= "</ul>\n";
  37. return $output;
  38. }
  39. // Default: http://blog, not http://blog/
  40. public function show(Application $app, $id) {
  41. if (!isset (static::POSTS[$id])) {
  42. // Will trigger the error() (or built-in) error handler.1
  43. $app->abort(Response::HTTP_NOT_FOUND, "Post $id does not exist.");
  44. }
  45. $post = static::POSTS[$id];
  46. return "<h1> {$post['title']}</h1>" . "<p> {$post['body']} </p>";
  47. }
  48. // Encode response manually.
  49. public function json(Application $app) {
  50. return $app->json(static::POSTS);
  51. }
  52. // Rely on the view handler.
  53. public function jsonView() {
  54. return static::POSTS;
  55. }
  56. }