【问题标题】:Unable to inject SecurityContext with services无法使用服务注入 SecurityContext
【发布时间】:2013-12-17 05:14:46
【问题描述】:

我看过很多关于这个的帖子,但我不明白我做错了什么。

services.yml:

parameters:

services:
    bar.menu_builder:
        class: Foo\BarBundle\Menu\MenuBuilder
        arguments: [ @security.context ]

菜单生成器:

namespace Foo\BarBundle\Menu;

use Symfony\Component\Security\Core\SecurityContextInterface;
use Knp\Menu\FactoryInterface;

class MenuBuilder {

    protected $securityContext;
    protected $isLoggedIn;

    public function __construct(SecurityContextInterface $securityContext) {
        $this->securityContext = $securityContext;
        $this->isLoggedIn = $this->securityContext->isGranted('IS_AUTHENTICATED_FULLY');
    }

    // other methods
}

但是没有通过SecurityContext,因为我得到了这个异常:

ContextErrorException:可捕获的致命错误:传递给 Foo\BarBundle\Menu\MenuBuilder::__construct() 的参数 1 必须实现接口 Symfony\Component\Security\Core\SecurityContextInterface,没有给出

有什么想法吗?

【问题讨论】:

  • 只是出于好奇,因为我已经多次看到此错误并且每次都是导致此错误的相同问题,您如何检索 bar.menu_builder 服务?你能给我们一个相关代码的sn-p吗?

标签: php symfony


【解决方案1】:

应该引用服务参数。

parameters:

services:
    bar.menu_builder:
        class: Foo\BarBundle\Menu\MenuBuilder
        arguments: ["@security.context"]

【讨论】:

  • 尝试清除缓存。或者检查您是否导入了 services.yml
【解决方案2】:

您是否在 config.yml 中导入了 security.yml?像这样:

imports:
    - { resource: parameters.yml }
    - { resource: security.yml }

另外,你必须让你的对象通过容器,像这样:

$this->get('bar.menu_builder');

如果这不起作用,那么您可以尝试清空缓存,以便重新编译容器。

史蒂芬

【讨论】:

    【解决方案3】:

    我不确定我为什么会遇到这个问题(我还是 Symfony2 的初学者),但我已经设法解决了。

    我添加了另一个服务来呈现我的菜单(请参阅here):

    bar.menu.main:
        class: Knp\Menu\MenuItem # the service definition requires setting the class
        factory_service: bar.menu_builder
        factory_method: createMainMenu
        arguments: ["@knp_menu.factory"]
        scope: request # needed as we have the request as a dependency here
        tags:
          - { name: knp_menu.menu, alias: main } # The alias is what is used to retrieve the menu
    

    并改变:

    {{ knp_menu_render('BarBundle:MenuBuilder:createMainMenu') }}
    

    为:

    {{ knp_menu_render('main') }}
    

    我认为,正如@Steffen Brem 和@DonCallisto 所建议的那样,bar.menu_builder 从未被检索到。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-27
      • 2014-07-01
      • 1970-01-01
      • 2016-11-17
      • 1970-01-01
      • 2019-05-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多