SessionAwareController.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. namespace App\Controller;
  3. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  4. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  8. /**
  9. * Class SessionAwareController demonstrates session usage.
  10. *
  11. * @package App\Controller
  12. */
  13. class SessionAwareController extends AbstractController {
  14. /**
  15. * @param \Symfony\Component\HttpFoundation\Session\SessionInterface $session
  16. *
  17. * @return \Symfony\Component\HttpFoundation\Response
  18. *
  19. * @Route(
  20. * name = "session-get",
  21. * path = "session/get"
  22. * )
  23. */
  24. public function getValue(SessionInterface $session) {
  25. $q = $session->has('q') ? $session->get('q') : NULL;
  26. if ($q) {
  27. $this->addFlash('info', "Q was found to be $q");
  28. }
  29. return new Response($q ? "Q is $q" : "Q is not set");
  30. }
  31. /**
  32. * @param \Symfony\Component\HttpFoundation\Session\SessionInterface $session
  33. * @param \Symfony\Component\HttpFoundation\Request $request
  34. *
  35. * @return \Symfony\Component\HttpFoundation\Response
  36. *
  37. * @Route(
  38. * name = "session-set",
  39. * path = "session/set"
  40. * )
  41. */
  42. public function setValue(SessionInterface $session, Request $request) {
  43. $q = $request->query->has('q') ? (int) $request->query->get('q') : 0;
  44. $session->set('q', $q);
  45. $this->addFlash('info', "Q was set to $q");
  46. return new Response("Set q to $q");
  47. }
  48. }