Reputation: 9279
I want to use my user session in a service with Symfony.
So, i have in my controller :
$service = $this->container->get('myservice');
$timeline = $service->getThing();
I need, in the function getThing()
, retrieve my user session.
I don't want to add the session like getThing($session)
How can i do that ?
Upvotes: 2
Views: 4735
Reputation: 7902
As @Igor says, inject session (and security context) into your controller (as it is a service).
Services.yml
services:
my.controller:
class: "%mybundle.controller.foo.class%"
arguments: [@session, @security.context]
Controller;
<?php
use Symfony\Component\HttpFoundation\Session\Session;
class Foo
{
private $sessionManager;
private $securityContext;
public function __construct(Session $session, $security_context)
{
$this->sessionMananger = $session;
$this->securityContext = $security_context;
}
public function someAction()
{
$id = $this->getId();
}
private function getId()
{
return $this->securityContext->getToken()->getUser()->getId();
}
}
Upvotes: 4
Reputation: 9246
You can inject session to your service. Session key in container is @session
.
Upvotes: 1