我创建服务但它不起作用
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')));
}
}
}
}
这是我的课
Hello123 --> I need "1"
Bye45 --> I need "4"
Container.php第268行中的ServiceNotFoundException:您已请求过 一个不存在的服务“security.context”。
答案 0 :(得分:48)
2.6中已弃用security.context
服务,并分为两个新服务:security.authorization_checker
和security.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')) { ... }
this声明中的更多信息
希望这个帮助
答案 1 :(得分:2)
以下示例将起作用:
/*Symfony 4.1.3*/
$user = $this->get('security.token_storage')->getToken()->getUser();
echo $user->getId(); // USER ID SESSION