Browse Source

Ch. 4: Using session data and flash messages. Extending layouts.

Frederic G. MARAND 6 years ago
parent
commit
b7e8aabb9f

+ 1 - 0
src/Controller/LuckyController.php

@@ -7,6 +7,7 @@ use Psr\Log\LoggerInterface;
 use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
 use Symfony\Bundle\FrameworkBundle\Controller\Controller;
 use Symfony\Component\HttpFoundation\Request;
+use Symfony\Component\HttpFoundation\Session\SessionInterface;
 
 class LuckyController extends Controller {
 

+ 8 - 3
src/Controller/SessionAwareController.php

@@ -3,6 +3,7 @@
 namespace App\Controller;
 
 use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
+use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
 use Symfony\Component\HttpFoundation\Request;
 use Symfony\Component\HttpFoundation\Response;
 use Symfony\Component\HttpFoundation\Session\SessionInterface;
@@ -12,7 +13,7 @@ use Symfony\Component\HttpFoundation\Session\SessionInterface;
  *
  * @package App\Controller
  */
-class SessionAwareController {
+class SessionAwareController extends AbstractController {
 
   /**
    * @param \Symfony\Component\HttpFoundation\Session\SessionInterface $session
@@ -24,8 +25,11 @@ class SessionAwareController {
    *   path = "session/get"
    * )
    */
-  public function get(SessionInterface $session) {
+  public function getValue(SessionInterface $session) {
     $q = $session->has('q') ? $session->get('q') : NULL;
+    if ($q) {
+      $this->addFlash('info', "Q was found to be $q");
+    }
     return new Response($q ? "Q is $q" : "Q is not set");
 
   }
@@ -41,9 +45,10 @@ class SessionAwareController {
    *   path = "session/set"
    * )
    */
-  public function set(SessionInterface $session, Request $request) {
+  public function setValue(SessionInterface $session, Request $request) {
     $q = $request->query->has('q') ? (int) $request->query->get('q') : 0;
     $session->set('q', $q);
+    $this->addFlash('info', "Q was set to $q");
     return new Response("Set q to $q");
   }
 }

+ 5 - 0
templates/base.html.twig

@@ -6,6 +6,11 @@
         {% block stylesheets %}{% endblock %}
     </head>
     <body>
+        {% for message in app.flashes('info') %}
+        <div class="flash-info">
+            {{ message }}
+        </div>
+        {% endfor %}
         {% block body %}{% endblock %}
         {% block javascripts %}{% endblock %}
     </body>

+ 4 - 0
templates/lucky/number.html.twig

@@ -1 +1,5 @@
+{% extends 'base.html.twig' %}
+
+{% block body %}
 <p>Your lucky number is {{ number }}.</p>
+{% endblock %}