26

我创建了服务,但它不起作用

services:
    redirectionListener:
          class: Front\EcommerceBundle\Listener\RedirectionListener
          arguments: ["@service_container","@session"]
          tags:
            - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }

这是我的课

namespace Front\EcommerceBundle\Listener;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;

class RedirectionListener
{
    public function __construct(ContainerBuilder $container, Session $session)
    {
        $this->session = $session;
        $this->router = $container->get('router');
        $this->securityContext = $container->get('security.context');
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        $route = $event->getRequest()->attributes->get('_route');

        if ($route == 'livraison' || $route == 'validation') {
            if ($this->session->has('panier')) {
                if (count($this->session->get('panier')) == 0)
                    $event->setResponse(new RedirectResponse($this->router->generate('panier')));
            }

            if (!is_object($this->securityContext->getToken()->getUser())) {
                $this->session->getFlashBag()->add('notification','Vous devez vous identifier');
                $event->setResponse(new RedirectResponse($this->router->generate('fos_user_security_login')));
            }
        }
    }
}

Container.php 第 268 行中的 ServiceNotFoundException:您请求了一个不存在的服务“security.context”。

4

2 回答 2

54

security.context服务在 2.6 中已弃用,并分为两个新服务:security.authorization_checkersecurity.token_storage.

与之前版本的框架有一些不同的用法:

// Symfony 2.5
$user = $this->get('security.context')->getToken()->getUser();
// Symfony 2.6
$user = $this->get('security.token_storage')->getToken()->getUser();

// Symfony 2.5
if (false === $this->get('security.context')->isGranted('ROLE_ADMIN')) { ... }
// Symfony 2.6
if (false === $this->get('security.authorization_checker')->isGranted('ROLE_ADMIN')) { ... }

公告中的更多信息

希望这有帮助

于 2016-04-10T17:38:08.557 回答
3

以下示例将起作用:

/*Symfony 4.1.3*/

$user = $this->get('security.token_storage')->getToken()->getUser();

echo $user->getId(); // USER ID SESSION
于 2018-08-23T16:54:26.060 回答