php - 如何在 Symfony KNP 菜单包中注册自定义选民?

标签 php symfony knpmenubundle

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

所以我知道更改供应商文件夹的内容是一种不好的做法。我的问题是,如何应用这些更改?我猜我必须创建自己的 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;
} 

在我的示例中,我的选民让项目 extra regex 工作。

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

希望对你有帮助

关于php - 如何在 Symfony KNP 菜单包中注册自定义选民?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35749351/

相关文章:

php - 如何使用 Datamapper 计算 Codeigniter 中查询返回的行数

symfony - phpunit 中的错误状态代码

mysql - SQL 子查询 IN SELECT [Symfony3]

php - 如何在 doctrine2 中找到实体

symfony2.1 捆绑版本混淆,用于 symfony 和奏鸣曲 admin/knp 菜单捆绑

symfony - 参数可为空且未提供空值

php - 在 codeigniter 中转换查询

php - 尝试在 mysql 中更新/插入 20k 记录,但它的工作速度非常慢,有什么建议吗?

PHP FOREACH ARRAY问题