1

I'm trying to figure out how to inject Drupal services into a custom service class. The class in question is my MenuService which builds an associative array of menu items which will be encoded to json and sent as a response for my custom REST endpoint ( /api/menu/{menu_name} ).

As a part of that, I need three classes:

\Drupal\Core\Path\AliasManager

\Drupal\Core\Menu\MenuTreeParameters

\Drupal\Core\Menu\MenuLinkTree

Any help on tracking down the MenuTreeParameters service would be helpful. I don't see it on this list. If it's not a defined service, can it be injected?

Note: Made some edits as I answered most of my own question

1

Alright, I think I figured it out. It should look something like this:

I couldn't find the service name anywhere for MenuTreeParameters so it's omitted in the examples for now.

I setup my menu service in rest_api.services.yml

services:
  rest_api.menu_service:
    class: Drupal\rest_api\Services\MenuService
    arguments: ['@path.alias_manager', '@menu.link_tree']

And created my service:

namespace Drupal\rest_api\Services;

use \Drupal\Core\Menu\MenuLinkTree;
use \Drupal\Core\Path\AliasManager;
use \Drupal\Core\Menu\MenuTreeParameters;

class MenuService {

  protected $aliasManager;

  public function __construct(AliasManager $aliasManager, MenuLinkTree $menuTree) {
    $this->aliasManager = $aliasManager;
    $this->menuTree = $menuTree;
    $this->items = array();
  }

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.