简体   繁体   English

您已请求不存在的服务“security.context”

[英]You have requested a non-existent service “security.context”

i create service but it doesn't work 我创建服务但它不起作用

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

and this my class 这是我的课

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

ServiceNotFoundException in Container.php line 268: You have requested a non-existent service "security.context". Container.php第268行中的ServiceNotFoundException:您已请求不存在的服务“security.context”。

The security.context service was deprecated in the 2.6 and split into two new services: security.authorization_checker and security.token_storage . security.context服务在2.6中已弃用,并分为两个新服务: security.authorization_checkersecurity.token_storage

Some different usage from the prior version of the framework: 与先前版本的框架有一些不同的用法:

// 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')) { ... }

More info in this announcement 公告中的更多信息

Hope this help 希望这有帮助

Following example will work: 以下示例将起作用:

/*Symfony 4.1.3*/

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

echo $user->getId(); // USER ID SESSION

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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