0
votes

I'm trying to use session variables in my custom service.

I already set add the following lines to services.yaml

MySession:
    class: App\Services\SessionTest
    arguments: ['@session', '@service_container']

And my SessionTest looks like this

namespace App\Services;

use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpFoundation\Request;

class SessionTest
{
    public $session;

    public function __construct()
    {

    }
    public function index()
    {
        echo "<pre>";
        var_dump($this->session);
        echo "</pre>";
    }
}

And receive this error: Too few arguments to function App\Services\SessionTest::__construct(), 0 passed in /var/www/app.dev/src/Controller/OrdersController.php on line 33 and exactly 1 expected

1
From the error message it almost seems like you are trying to new SessionTest(); from the OrdersController? Furthermore, the __construct you posted does not indicate that the SessionInterface is being injected.Cerad
I already tried it with SessionInterface and receive the same error messagewinnerke
Very doubtful. But did you see the first part of my comment? Are you trying to new SessionTest or are you trying to inject it into the controller?Cerad
yes, I am trying to execute new SessionTest If I use your edition then receive NULLwinnerke
Okay. The php new operator knows nothing about Symfony's service container. Check the docs to see how to inject services such as your SessionTest into a controller. symfony.com/doc/current/…Cerad

1 Answers

0
votes

You are using constructor injection in your config, but it looks like you're trying to accept property injection in TestSession.

The container will be generated with code like approximately this:

new SessionTest(SessionInterface $session, ContainterInterface $container)

So you either need to change TestSession to accept '@session' and '@service_container' as constructor arguments:

protected $session;
protected $serviceContainer;

public function __construct(SessionInterface $session, ContainterInterface $serviceContainer)
{
    $this->sessions = $session;
    $this->serviceContainer = $container;
}

Or you need to change your config to something like this:

MySession:
    class: App\Services\SessionTest
    properties:
        session: '@session'
        serviceContainer: '@service_container'

You will also need to add

   public $serviceContainer;

to TestSession if you want to inject the service container as a property.