所以我决定在我的 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/