@@ -7,35 +7,26 @@ Session Management
7
7
8
8
The Symfony HttpFoundation component has a very powerful and flexible session
9
9
subsystem which is designed to provide session management through a clear
10
- object-oriented interface using a variety of session storage drivers.
11
-
12
- Sessions are used via the :class: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Session `
13
- implementation of :class: `Symfony\\ Component\\ HttpFoundation\\ Session\\ SessionInterface ` interface.
14
-
15
- .. caution ::
16
-
17
- Make sure your PHP session isn't already started before using the Session
18
- class. If you have a legacy session system that starts your session, see
19
- :doc: `Legacy Sessions </components/http_foundation/session_php_bridge >`.
20
-
21
- Quick example::
10
+ object-oriented interface using a variety of session storage drivers::
22
11
12
+ use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag;
23
13
use Symfony\Component\HttpFoundation\Session\Session;
14
+ use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
24
15
25
16
$session = new Session();
26
17
$session->start();
27
18
28
- // set and get session attributes
29
19
$session->set('name', 'Drak');
30
20
$session->get('name');
31
21
32
- // set flash messages
33
- $session->getFlashBag()->add('notice', 'Profile updated' );
22
+ // Pass a storage and a bag implementation explicitely
23
+ $session = new Session(new NativeSessionStorage(), new AttributeBag() );
34
24
35
- // retrieve messages
36
- foreach ($session->getFlashBag()->get('notice', []) as $message) {
37
- echo '<div class="flash-notice">'.$message.'</div>';
38
- }
25
+ .. caution ::
26
+
27
+ Make sure your PHP session isn't already started before using the Session
28
+ class. If you have a legacy session system that starts your session, see
29
+ :doc: `Legacy Sessions </components/http_foundation/session_php_bridge >`.
39
30
40
31
.. note ::
41
32
@@ -56,286 +47,55 @@ Quick example::
56
47
This directive should be turned off in ``php.ini ``, in the web server directives or
57
48
in ``.htaccess ``.
58
49
59
- Session API
60
- ~~~~~~~~~~~
61
-
62
- The :class: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Session ` class implements
63
- :class: `Symfony\\ Component\\ HttpFoundation\\ Session\\ SessionInterface `.
64
-
65
- The :class: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Session ` has the
66
- following API, divided into a couple of groups.
67
-
68
- Session Workflow
69
- ................
70
-
71
- :method: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Session::start `
72
- Starts the session - do not use ``session_start() ``.
73
-
74
- :method: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Session::migrate `
75
- Regenerates the session ID - do not use ``session_regenerate_id() ``.
76
- This method can optionally change the lifetime of the new cookie that will
77
- be emitted by calling this method.
78
-
79
- :method: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Session::invalidate `
80
- Clears all session data and regenerates session ID. Do not use ``session_destroy() ``.
81
-
82
- :method: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Session::getId `
83
- Gets the session ID. Do not use ``session_id() ``.
84
-
85
- :method: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Session::setId `
86
- Sets the session ID. Do not use ``session_id() ``.
87
-
88
- :method: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Session::getName `
89
- Gets the session name. Do not use ``session_name() ``.
90
-
91
- :method: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Session::setName `
92
- Sets the session name. Do not use ``session_name() ``.
93
-
94
- Session Attributes
95
- ..................
96
-
97
- The session attributes are stored internally in a "Bag", a PHP object that acts
98
- like an array. They can be set, removed, checked, etc. using the methods
99
- explained later in this article for the ``AttributeBagInterface `` class. See
100
- :ref: `attribute-bag-interface `.
101
-
102
- In addition, a few methods exist for "Bag" management:
103
-
104
- :method: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Session::registerBag `
105
- Registers a :class: `Symfony\\ Component\\ HttpFoundation\\ Session\\ SessionBagInterface `.
106
-
107
- :method: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Session::getBag `
108
- Gets a :class: `Symfony\\ Component\\ HttpFoundation\\ Session\\ SessionBagInterface ` by
109
- bag name.
110
-
111
- :method: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Session::getFlashBag `
112
- Gets the :class: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Flash\\ FlashBagInterface `.
113
- This is just a shortcut for convenience.
114
-
115
- Session Metadata
116
- ................
117
-
118
- :method: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Session::getMetadataBag `
119
- Gets the :class: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Storage\\ MetadataBag `
120
- which contains information about the session.
121
-
122
- Session Data Management
123
- ~~~~~~~~~~~~~~~~~~~~~~~
50
+ Attributes
51
+ ----------
124
52
125
53
PHP's session management requires the use of the ``$_SESSION `` super-global,
126
54
however, this interferes somewhat with code testability and encapsulation in an
127
55
OOP paradigm. To help overcome this, Symfony uses *session bags * linked to the
128
- session to encapsulate a specific dataset of attributes or flash messages .
56
+ session to encapsulate a specific dataset of attributes.
129
57
130
58
This approach also mitigates namespace pollution within the ``$_SESSION ``
131
59
super-global because each bag stores all its data under a unique namespace.
132
60
This allows Symfony to peacefully co-exist with other applications or libraries
133
61
that might use the ``$_SESSION `` super-global and all data remains completely
134
62
compatible with Symfony's session management.
135
63
136
- Symfony provides two kinds of storage bags, with two separate implementations.
137
- Everything is written against interfaces so you may extend or create your own
138
- bag types if necessary.
139
-
140
- :class: `Symfony\\ Component\\ HttpFoundation\\ Session\\ SessionBagInterface ` has
141
- the following API which is intended mainly for internal purposes:
142
-
143
- :method: `Symfony\\ Component\\ HttpFoundation\\ Session\\ SessionBagInterface::getStorageKey `
144
- Returns the key which the bag will ultimately store its array under in ``$_SESSION ``.
145
- Generally this value can be left at its default and is for internal use.
146
-
147
- :method: `Symfony\\ Component\\ HttpFoundation\\ Session\\ SessionBagInterface::initialize `
148
- This is called internally by Symfony session storage classes to link bag data
149
- to the session.
150
-
151
- :method: `Symfony\\ Component\\ HttpFoundation\\ Session\\ SessionBagInterface::getName `
152
- Returns the name of the session bag.
153
-
154
- :method: `Symfony\\ Component\\ HttpFoundation\\ Session\\ SessionBagInterface::clear `
155
- Clears out data from the bag.
156
-
157
- .. _attribute-bag-interface :
158
-
159
- Attributes
160
- ~~~~~~~~~~
161
-
162
- The purpose of the bags implementing the :class: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Attribute\\ AttributeBagInterface `
163
- is to handle session attribute storage. This might include things like user ID,
164
- and "Remember Me" login settings or other user based state information.
165
-
166
- :class: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Attribute\\ AttributeBag `
167
- This is the standard default implementation.
168
-
169
- :class: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Attribute\\ NamespacedAttributeBag `
170
- This implementation allows for attributes to be stored in a structured namespace.
171
-
172
- .. deprecated :: 5.3
64
+ A bag is a PHP object that acts like an array::
173
65
174
- The ``NamespacedAttributeBag `` class is deprecated since Symfony 5.3.
175
- If you need this feature, you will have to implement the class yourself.
176
-
177
- :class: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Attribute\\ AttributeBagInterface `
178
- has the API
179
-
180
- :method: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Attribute\\ AttributeBagInterface::set `
181
- Sets an attribute by name (``set('name', 'value') ``).
182
-
183
- :method: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Attribute\\ AttributeBagInterface::get `
184
- Gets an attribute by name (``get('name') ``) and can define a default
185
- value when the attribute doesn't exist (``get('name', 'default_value') ``).
186
-
187
- :method: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Attribute\\ AttributeBagInterface::all `
188
- Gets all attributes as an associative array of ``name => value ``.
189
-
190
- :method: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Attribute\\ AttributeBagInterface::has `
191
- Returns ``true `` if the attribute exists.
192
-
193
- :method: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Attribute\\ AttributeBagInterface::replace `
194
- Sets multiple attributes at once using an associative array (``name => value ``).
195
- If the attributes existed, they are replaced; if not, they are created.
196
-
197
- :method: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Attribute\\ AttributeBagInterface::remove `
198
- Deletes an attribute by name and returns its value.
199
-
200
- :method: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Attribute\\ AttributeBagInterface::clear `
201
- Deletes all attributes.
202
-
203
- Example::
204
-
205
- use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag;
206
- use Symfony\Component\HttpFoundation\Session\Session;
207
- use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
66
+ // set and get session attributes
67
+ $session->set('name', 'Drak');
68
+ $session->get('name');
208
69
209
- $session = new Session(new NativeSessionStorage(), new AttributeBag());
210
- $session->set('token', 'a6c1e0b6');
211
- // ...
212
- $token = $session->get('token');
213
70
// if the attribute may or may not exist, you can define a default value for it
214
71
$token = $session->get('attribute-name', 'default-attribute-value');
215
- // ...
216
- $session->clear();
217
-
218
- .. _namespaced-attributes :
219
-
220
- Namespaced Attributes
221
- .....................
222
-
223
- Any plain key-value storage system is limited in the extent to which
224
- complex data can be stored since each key must be unique. You can achieve
225
- namespacing by introducing a naming convention to the keys so different parts of
226
- your application could operate without clashing. For example, ``module1.foo `` and
227
- ``module2.foo ``. However, sometimes this is not very practical when the attributes
228
- data is an array, for example a set of tokens. In this case, managing the array
229
- becomes a burden because you have to retrieve the array then process it and
230
- store it again::
231
-
232
- $tokens = [
233
- 'tokens' => [
234
- 'a' => 'a6c1e0b6',
235
- 'b' => 'f4a7b1f3',
236
- ],
237
- ];
238
-
239
- So any processing of this might quickly get ugly, even adding a token to the array::
240
-
241
- $tokens = $session->get('tokens');
242
- $tokens['c'] = $value;
243
- $session->set('tokens', $tokens);
244
-
245
- .. deprecated :: 5.3
246
-
247
- The ``NamespacedAttributeBag `` class is deprecated since Symfony 5.3.
248
- If you need this feature, you will have to implement the class yourself.
249
-
250
- With structured namespacing, the key can be translated to the array
251
- structure like this using a namespace character (which defaults to ``/ ``)::
252
72
253
73
// ...
254
- use Symfony\Component\HttpFoundation\Session\Attribute\NamespacedAttributeBag;
255
-
256
- $session = new Session(new NativeSessionStorage(), new NamespacedAttributeBag());
257
- $session->set('tokens/c', $value);
74
+ $session->clear();
258
75
259
76
Flash Messages
260
- ~~~~~~~~~~~~~~
261
-
262
- The purpose of the :class: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Flash\\ FlashBagInterface `
263
- is to provide a way of setting and retrieving messages on a per session basis.
264
- The usual workflow would be to set flash messages in a request and to display them
265
- after a page redirect. For example, a user submits a form which hits an update
266
- controller, and after processing the controller redirects the page to either the
267
- updated page or an error page. Flash messages set in the previous page request
268
- would be displayed immediately on the subsequent page load for that session.
269
- This is however just one application for flash messages.
270
-
271
- :class: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Flash\\ AutoExpireFlashBag `
272
- In this implementation, messages set in one page-load will
273
- be available for display only on the next page load. These messages will auto
274
- expire regardless of if they are retrieved or not.
275
-
276
- :class: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Flash\\ FlashBag `
277
- In this implementation, messages will remain in the session until
278
- they are explicitly retrieved or cleared. This makes it possible to use ESI
279
- caching.
280
-
281
- :class: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Flash\\ FlashBagInterface `
282
- has the API
283
-
284
- :method: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Flash\\ FlashBagInterface::add `
285
- Adds a flash message to the stack of specified type.
286
-
287
- :method: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Flash\\ FlashBagInterface::set `
288
- Sets flashes by type; This method conveniently takes both single messages as
289
- a ``string `` or multiple messages in an ``array ``.
77
+ --------------
290
78
291
- :method: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Flash\\ FlashBagInterface::get `
292
- Gets flashes by type and clears those flashes from the bag.
293
-
294
- :method: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Flash\\ FlashBagInterface::setAll `
295
- Sets all flashes, accepts a keyed array of arrays ``type => [messages] ``.
296
-
297
- :method: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Flash\\ FlashBagInterface::all `
298
- Gets all flashes (as a keyed array of arrays) and clears the flashes from the bag.
299
-
300
- :method: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Flash\\ FlashBagInterface::peek `
301
- Gets flashes by type (read only).
302
-
303
- :method: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Flash\\ FlashBagInterface::peekAll `
304
- Gets all flashes (read only) as a keyed array of arrays.
305
-
306
- :method: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Flash\\ FlashBagInterface::has `
307
- Returns true if the type exists, false if not.
308
-
309
- :method: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Flash\\ FlashBagInterface::keys `
310
- Returns an array of the stored flash types.
311
-
312
- :method: `Symfony\\ Component\\ HttpFoundation\\ Session\\ Flash\\ FlashBagInterface::clear `
313
- Clears the bag.
314
-
315
- For simple applications it is usually sufficient to have one flash message per
316
- type, for example a confirmation notice after a form is submitted. However,
317
- flash messages are stored in a keyed array by flash ``$type `` which means your
318
- application can issue multiple messages for a given type. This allows the API
319
- to be used for more complex messaging in your application.
320
-
321
- Examples of setting multiple flashes::
79
+ Attributes can also be used to store "flash messages" via a specific bag
80
+ accessible with ``getFlashBag() ``::
322
81
323
82
use Symfony\Component\HttpFoundation\Session\Session;
324
83
325
84
$session = new Session();
326
85
$session->start();
327
86
87
+ // retrieve the flash messages bag
88
+ $flashes = $session->getFlashBag();
89
+
328
90
// add flash messages
329
- $session->getFlashBag() ->add(
91
+ $flashes ->add(
330
92
'warning',
331
93
'Your config file is writable, it should be set read-only'
332
94
);
333
- $session->getFlashBag()->add('error', 'Failed to update name');
334
- $session->getFlashBag()->add('error', 'Another error');
335
-
336
- Displaying the flash messages might look as follows.
95
+ $flashes->add('error', 'Failed to update name');
96
+ $flashes->add('error', 'Another error');
337
97
338
- Display one type of message ::
98
+ Displaying the flash messages might look as follows ::
339
99
340
100
// display warnings
341
101
foreach ($session->getFlashBag()->get('warning', []) as $message) {
@@ -347,8 +107,7 @@ Display one type of message::
347
107
echo '<div class="flash-error">'.$message.'</div>';
348
108
}
349
109
350
- Compact method to process display all flashes at once::
351
-
110
+ // Display all flashes at once
352
111
foreach ($session->getFlashBag()->all() as $type => $messages) {
353
112
foreach ($messages as $message) {
354
113
echo '<div class="flash-'.$type.'">'.$message.'</div>';
0 commit comments