[HttpFoundation] Clarify behavior of session access via RequestStack to avoid auto-starting sessions #20891
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Symfony’s documentation states that sessions are automatically started when they are accessed (read, written, or even just checked), and it recommends avoiding session access for anonymous users to prevent unnecessary session cookies.
However, calling
Request::getSession()
orRequestStack::getSession()
can throw aSessionNotFoundException
if the session has not yet been started. This behavior contradicts the suggestion to "simply avoid accessing the session," since accessing it directly may cause an exception rather than just lazily starting the session as in previous versions where the session was injected viaSessionInterface
.For this reason, I believe it makes sense to remove the following line from the documentation:
"Sessions are automatically started whenever you read, write or even check for the existence of data in the session. This may hurt your application performance because all users will receive a session cookie. In order to prevent starting sessions for anonymous users, you must completely avoid accessing the session."
This guidance may no longer reflect the actual behavior, where trying to access a session that doesn't exist now results in an exception, not an automatic creation.
It’s possible that I’m misunderstanding the intended behavior. If that’s the case, I apologize and will be happy to close this pull request. I just wanted to raise the concern in case it helps clarify the documentation.