简体   繁体   中英

Use session in service with Symfony

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 ?

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();
    }
}

You can inject session to your service. Session key in container is @session .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM