Sessions
| Store in session | |
| Read back | |
| Flash messages | |
| Invalidate |
Store in session
The session is per visitor storage that survives across requests, ideal for a cart id or a chosen locale. Access it through the request stack service instead of global arrays.
Call set with a clear key and a small scalar value. Store ids and flags only, then reload full records from the database on each request.
namespace App\Service; use Symfony\Component\HttpFoundation\RequestStack; class CartService { public function __construct(private RequestStack $requestStack) { } public function add(int $id): void { $session = $this->requestStack->getSession(); $session->set("cart_id", $id); } }
Read back
Reading uses get with the same key plus a default for first time visitors. The default keeps code simple because no extra existence check is needed.
Pick defaults that clearly mean empty, such as zero for ids or an empty string for names. Cast the result when strict types matter for later logic.
namespace App\Service; use Symfony\Component\HttpFoundation\RequestStack; class CartService { public function __construct(private RequestStack $requestStack) { } public function current(): int { $session = $this->requestStack->getSession(); return $session->get("cart_id", 0); } }
Flash messages
Flash messages show one time notices such as saved or deleted after a redirect. They live in a special bag that removes each message once it is displayed.
Add a flash before redirecting so the next page can render it. Use short categories like notice or error so templates can style each kind.
namespace App\Service; use Symfony\Component\HttpFoundation\RequestStack; class NoticeService { public function __construct(private RequestStack $requestStack) { } public function saved(): void { $session = $this->requestStack->getSession(); $session->getFlashBag()->add("notice", "Saved"); } }
Invalidate
Invalidation ends the session completely by clearing data and issuing a fresh id. Use it on logout and after security sensitive changes such as password updates.
Call invalidate once, then redirect to a public page. A fresh empty session starts on the next visit without any leftover values.
namespace App\Service; use Symfony\Component\HttpFoundation\RequestStack; class LogoutService { public function __construct(private RequestStack $requestStack) { } public function logout(): void { $session = $this->requestStack->getSession(); $session->invalidate(); } }
Next: CSRF
Article author: Arthur Isaev