How to access a symfony session without declaring any variables? (Symfony components interacting with Legacy code use case)

Say I have a single line, not in a class anywhere, and I know the session has a variable called "foo" that I want to output.

In standard PHP, I could simply...

echo $_SESSION["foo"];

So what do I need to do in order to the equivalent using a symfony session? I'm not in a function, not in a class, not passing any variables from point A to point B, no $request variable, no $session. I simply want to output "foo" from the session. How do I go about doing this?

This is in a legacy codebase that has a fair chunk of procedurally written code.

1 answer

  • answered 2018-10-11 19:47 Dylan Pierce

    Option 1: since you are using PHP, you still could use the $_SESSION super global to access session variables.

    Option 2: otherwise you can use Symfony's Session class, documentation here:

    Option 3: create a helper that abstracts Symfony's session. In your composer.json file add a files definition in your autoload section:

       "autoload": {
            "files": ["src/helpers/SessionsHelper.php"]

    P.S. don't forget to composer dump-autoload.

    Now, inside of SessionsHelper you can create functions that are globally accessible:

    use Symfony\Component\HttpFoundation\Session\Session;
     * Retrieve a value from Session
     * @param $key [String]
     * @return [String]
    function getSessionValue($key)
       $session = new Session();
       return $session->get($key);

    Now you can use getSessionValue anywhere in code:

    echo getSessionValue('user_id');