Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit a19319e

Browse files
committedApr 4, 2024·
[HttpKernel] Document the MapSessionContext value resolver
1 parent 93a217e commit a19319e

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed
 

‎controller/value_resolver.rst

+7
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,13 @@ Symfony ships with the following value resolvers in the
110110
Injects a service if type-hinted with a valid service class or interface. This
111111
works like :doc:`autowiring </service_container/autowiring>`.
112112

113+
:class:`Symfony\\Component\\HttpKernel\\Controller\\ArgumentResolver\\SessionParameterValueResolver.php`
114+
Map type-hinted object into the session.
115+
116+
Because this is a :ref:`targeted value resolver <value-resolver-targeted>`,
117+
you'll have to use the :ref:`MapSessionParameter <session-mapping-session-context>` attribute
118+
in order to use this resolver.
119+
113120
:class:`Symfony\\Component\\HttpKernel\\Controller\\ArgumentResolver\\SessionValueResolver`
114121
Injects the configured session class implementing ``SessionInterface`` if
115122
type-hinted with ``SessionInterface`` or a class implementing

‎session.rst

+38
Original file line numberDiff line numberDiff line change
@@ -1328,6 +1328,44 @@ has to return an integer which will be used as TTL.
13281328
// Inject whatever dependencies you need to be able to resolve a TTL for the current session
13291329
->args([service('security')]);
13301330
1331+
1332+
.. _session-mapping-session-parameter:
1333+
1334+
Mapping the session to a DTO object
1335+
-----------------------------------
1336+
1337+
A possibility is to map the current session into an object that will read from/write to the session.
1338+
Let's say you declare the following DTO ::
1339+
1340+
namespace App\Model;
1341+
1342+
class PreferenceDTO
1343+
{
1344+
public bool $enableNotification = true;
1345+
public string $locale = "en";
1346+
}
1347+
1348+
You can then use the :class:`Symfony\\Component\\HttpKernel\\Attribute\\MapSessionParameter`
1349+
attribute in your controller::
1350+
1351+
use App\Model\PreferenceDTO;
1352+
use Symfony\Component\HttpFoundation\Response;
1353+
use Symfony\Component\HttpKernel\Attribute\MapSessionParameter;
1354+
1355+
// ...
1356+
1357+
public function dashboard(
1358+
#[MapSessionParameter] PreferenceDTO $preferencesDTO
1359+
): Response
1360+
{
1361+
// ...
1362+
}
1363+
1364+
The method will then receive an instance of your DTO linked with the session.
1365+
Value set in this object will be persisted in session and will be available for reading later.
1366+
1367+
The name of the parameter is used as the session key.
1368+
13311369
.. _locale-sticky-session:
13321370

13331371
Making the Locale "Sticky" during a User's Session

0 commit comments

Comments
 (0)