2

Drupal 7 has menu_link_load() to load a single menu item. What is the Drupal 8 equivalent?

2

Drupal 8 menu links are now content entities. The equivalent to loading a D7 menu link object would be loading a MenuLinkContent entity. This can be done via the static Drupal\menu_link_content\Entity\MenuLinkContent::load() method.

| improve this answer | |
  • 3
    I'd add the entity type manager method, too. Because it's pretty generic for any entity type. \Drupal::entityTypeManager()->getStorage('menu_link_content')->load($id); – leymannx Sep 21 at 17:49
2

It should be considered good practice to rely on the entity type manager to load entities. First, the pattern is easy to remember and looks the same for any entity type. Just replace menu_link_content with node or node_type or whatever. Second, it supports the dependency injection container to be used in OOP code.

\Drupal::entityTypeManager()->getStorage('menu_link_content')->load($id);

Read Working with the Entity API for more info.

Avoid using the static Entity::load() method in object oriented code. Instead use dependency injection to inject the entity type manager and load the entity with $this->entityTypeManager->getStorage($entity_type)->load($entity_id). This ensures that the code is properly decoupled and can be unit tested.

Also this issue is a nice read as well: Node::load($nid) vs. \Drupal::entityTypeManager()->getStorage('node')->load($nid)

Often I hear that \Drupal::entityTypeManager()->getStorage('node')->load($nid) should be used instead of Node::load($nid). Is argued that using the later is not recommended. I've searched in the relevant doc page, issue or change record but none of them could give me a clue why one is the preferred way, than the other.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.