A Matcher
is capable of determining if a menu item is the menu entry for the
current page, or an ancestor thereof. The default matcher implementation uses
the voter pattern.
Here is an example how to use the matcher:
use Knp\Menu\Matcher\Matcher;
$itemMatcher = new Matcher([new UriVoter(str_replace('/index.php', '', $_SERVER['REQUEST_URI']))]);
To use the Matcher
you have to pass it to your renderer. For the ListRenderer
,
this looks like:
use Knp\Menu\Renderer\ListRenderer;
new ListRenderer($itemMatcher);
KnpMenu provides some voters for standard cases:
RegexVoter
: checks if the request matches a regular expression you pass to the voterRouteVoter
: uses a Symfony request to check if the current route is same as the route of the menu itemUriVoter
: compare the URI of the menu item with the URI passed to the voterCallbackVoter
: allows matching based on a callback set asmatch_callback
underextras
option of the menu item
You can create your own voters by implementing VoterInterface
.
use Knp\Menu\Matcher\Voter\VoterInterface;
class MyAwesomeVoter implements VoterInterface
{
// Your code
}
Note: You can also write your own matcher that implements the MatcherInterface
if you need something different than the voter approach.
If you use the KnpMenuBundle, the RouteVoter is automatically loaded.