Browse Source

Ch. 4: Using session data.

Frederic G. MARAND 6 years ago
parent
commit
d230f127f7
2 changed files with 52 additions and 3 deletions
  1. 3 3
      config/packages/framework.yaml
  2. 49 0
      src/Controller/SessionAwareController.php

+ 3 - 3
config/packages/framework.yaml

@@ -5,9 +5,9 @@ framework:
     #http_method_override: true
 
     # uncomment this entire section to enable sessions
-    #session:
-    #    # With this config, PHP's native session handling is used
-    #    handler_id: ~
+    session:
+        # With this config, PHP's native session handling is used
+        handler_id: ~
 
     #esi: ~
     #fragments: ~

+ 49 - 0
src/Controller/SessionAwareController.php

@@ -0,0 +1,49 @@
+<?php
+
+namespace App\Controller;
+
+use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
+use Symfony\Component\HttpFoundation\Request;
+use Symfony\Component\HttpFoundation\Response;
+use Symfony\Component\HttpFoundation\Session\SessionInterface;
+
+/**
+ * Class SessionAwareController demonstrates session usage.
+ *
+ * @package App\Controller
+ */
+class SessionAwareController {
+
+  /**
+   * @param \Symfony\Component\HttpFoundation\Session\SessionInterface $session
+   *
+   * @return \Symfony\Component\HttpFoundation\Response
+   *
+   * @Route(
+   *   name = "session-get",
+   *   path = "session/get"
+   * )
+   */
+  public function get(SessionInterface $session) {
+    $q = $session->has('q') ? $session->get('q') : NULL;
+    return new Response($q ? "Q is $q" : "Q is not set");
+
+  }
+
+  /**
+   * @param \Symfony\Component\HttpFoundation\Session\SessionInterface $session
+   * @param \Symfony\Component\HttpFoundation\Request $request
+   *
+   * @return \Symfony\Component\HttpFoundation\Response
+   *
+   * @Route(
+   *   name = "session-set",
+   *   path = "session/set"
+   * )
+   */
+  public function set(SessionInterface $session, Request $request) {
+    $q = $request->query->has('q') ? (int) $request->query->get('q') : 0;
+    $session->set('q', $q);
+    return new Response("Set q to $q");
+  }
+}