Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Accessing session from request stack #150

Open
szymach opened this issue Dec 24, 2021 · 0 comments
Open

Accessing session from request stack #150

szymach opened this issue Dec 24, 2021 · 0 comments

Comments

@szymach
Copy link

szymach commented Dec 24, 2021

Hello,

I have a private library for handling translations, which works in a way where you have a translatable entity and a collection of translation entities for it, each for a different locale. Each time the translatable entity is being created or modified via Doctrine's Unit of Work, the current locale is being checked and either a new translation is created or an existing one is modified. The locale is checked like so, through a dedicated service:

final class LocaleProvider 
{
    private const SESSION_KEY = 'key';

    private RequestStack $requestStack;
    private string $defaultLocale; // `%kernel.default_locale%`

    public function getLocale(): string
    {
        $savedLocale = $this->getSavedLocale();
        if (null !== $savedLocale) {
            return $savedLocale;
        }

        $request = $this->requestStack->getCurrentRequest();
        if (null !== $request) {
            return $request->getLocale();
        }

        return $this->defaultLocale;
    }

    private function getSavedLocale(): ?string
    {
        $session = $this->getSession();
        if (null === $session) {
            return null;
        }

        return $session->get(self::SESSION_KEY);
    }

    private function getSession(): ?SessionInterface
    {
        $currentRequest = $this->requestStack->getCurrentRequest();
        if (null === $currentRequest) {
            return null;
        }

        return $currentRequest->getSession();
    }
}

The library worked just fine until I switched from accessing the session service directly from the container to accessing the instance from the request_stack, as seen above. Basically, $this->requestStack->getCurrentRequest() (or any other of it's methods) never returns an actual request. From analyzing the code it seems that there is a RequestStack being created in the HttpKernel used by Symfony module, but from what I have checked it is not the same instance that gets injected into my LocaleProvider service. Is there anything that I am missing here?

@szymach szymach changed the title Getting session storage to work between requests Accessing session from request stack Dec 24, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant