Working with menu links

I mentioned earlier that MenuLinkTreeElement objects wrap individual menu links, but what can you do with these programmatically if you choose to work with this data yourself and not rely on the menu theme hook? Let's cover a few common things you can do.

First of all, the most important thing to do is to access the menu link plugin. You can do so directly, as it is a public property on the MenuLinkTreeElement:

$link = $data->link;  

Now, you can work with the $link variable, which is an instance of MenuLinkInterface, and more often than not, an actual MenuLinkDefault instance that extends the MenuLinkBase class.

So if we inspect that interface, we can see a number of handy methods. The most common of these will be the getters for the menu link definition we saw earlier when defining the plugins. The getUrlObject() is also an important method that transforms the route of the menu link into a Url object that we already know how to use. If the menu link is created in the UI, it could be that it has no route but only a path, in which case, this method will still be able to construct a common Url object based on that path.

If you have your hands on a menu link that is not from a tree where you have already handled access, you can ask the Url object to check access before actually using it:

$access = $url->access()  

If the link is not routed, the access will always return TRUE because it means that the link is external, or, in any case, no access check can be done. We will talk more about the access system in a separate chapter.