From 711aa6b2368d1e22e650e367cb6d2e15077cc877 Mon Sep 17 00:00:00 2001 From: Julien Tattevin Date: Tue, 2 Apr 2024 17:59:20 +0200 Subject: [PATCH] [HttpKernel] Document the MapSessionParameter value resolver --- controller/value_resolver.rst | 7 ++++++ session.rst | 41 +++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/controller/value_resolver.rst b/controller/value_resolver.rst index 5f0f7484e46..963188ded5a 100644 --- a/controller/value_resolver.rst +++ b/controller/value_resolver.rst @@ -110,6 +110,13 @@ Symfony ships with the following value resolvers in the Injects a service if type-hinted with a valid service class or interface. This works like :doc:`autowiring `. +:class:`Symfony\\Component\\HttpKernel\\Controller\\ArgumentResolver\\SessionParameterValueResolver.php` + Pass a session parameter to a controller argument. + + Because this is a :ref:`targeted value resolver `, + you'll have to use the :ref:`MapSessionParameter ` attribute + in order to use this resolver. + :class:`Symfony\\Component\\HttpKernel\\Controller\\ArgumentResolver\\SessionValueResolver` Injects the configured session class implementing ``SessionInterface`` if type-hinted with ``SessionInterface`` or a class implementing diff --git a/session.rst b/session.rst index 4bf373dc6a9..2f20c03fe8b 100644 --- a/session.rst +++ b/session.rst @@ -1328,6 +1328,47 @@ has to return an integer which will be used as TTL. // Inject whatever dependencies you need to be able to resolve a TTL for the current session ->args([service('security')]); + +.. _session-passing-session-parameter: + +Passing a session parameter to a controller argument +---------------------------------------------------- + +A possibility is to pass a session parameter to a controller argument. +Let's say you declare the following DTO :: + + namespace App\Model; + + class UserPreference + { + public bool $enableNotification = true; + public string $locale = "en"; + } + +You can then use the :class:`Symfony\\Component\\HttpKernel\\Attribute\\MapSessionParameter` +attribute in your controller:: + + use App\Model\UserPreference; + use Symfony\Component\HttpFoundation\Response; + use Symfony\Component\HttpKernel\Attribute\MapSessionParameter; + + // ... + + public function dashboard( + #[MapSessionParameter] UserPreference $userPreferences + ): Response + { + // ... + } + +The method will then receive an instance of your DTO linked with the session. +Value set in this object will be persisted in session and will be available for reading later. + +The name of the parameter is used as the session key. + +This attribute work with classes and interfaces. +If you use an interface, you must provide a default value or make the parameter nullable, if the session isn't set, it will not be possible to create a new instance when resolving the value. + .. _locale-sticky-session: Making the Locale "Sticky" during a User's Session