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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.