如何在Symfony KNP菜单包中注册自定义投票者


How to register custom voter in Symfony KNP Menu Bundle?

所以我决定在我的Symfony项目中使用KnpMenuBundle,但为了让菜单按我的意图工作,我在/vendor/knplabs/knp-menu/src/Knp/Menu/Matcher/Voter/RouteVoter.php中添加了2行。

所以我知道更改供应商文件夹的内容是一种不好的做法。我的问题是,如何应用这些更改?我猜我必须创建自己的 Voter 类,扩展 RouteVoter 并以某种方式向 Symfony 注册它。在互联网上,我找不到如何做到这一点。

有什么想法吗?谢谢,迈克。

要注册自定义投票者,您必须在项目中创建自定义选民并将其注册为服务。

你的选民应该看起来像这样

class RegexVoter implements VoterInterface
{
    /**
     * @var RequestStack
     */
    private $requestStack;
    /**
     * @param RequestStack $requestStack
     */
    public function __construct(RequestStack $requestStack)
    {
        $this->requestStack = $requestStack;
    }
    /**
     * {@inheritdoc}
     */
    public function matchItem(ItemInterface $item)
    {
        $childRegex = $item->getExtra('regex');
        if ($childRegex !== null && preg_match($childRegex, $this->requestStack->getCurrentRequest()->getPathInfo())) {
            return true;
        }
        return;
    }
}

将其注册为这样的服务

menu.voter.regex:
    class: AppBundle'Menu'Matcher'Voter'RegexVoter
    arguments: [ '@request_stack' ]
    tags:
        - { name: knp_menu.voter }

然后,您必须在menuBuilder中实例化您的选民

private $regexVoter;
public function __construct(RegexVoter $regexVoter)
{
    $this->regexVoter = $regexVoter;
} 

在我的示例中,我的选民获得了额外的regex来工作的项目。

我认为你必须修改并使用你自己的逻辑。

我希望这对你有帮助