0

Over time, I have created some contributed module projects for D7. With D7 EOL not too distant in the future, I need to convert those to D8.

I've just started out doing this, and I've found the OO-style of D8 very different from the procedural style of D7.

For instance, I want to call the public function getTopics() that is part of the Advanced Help project. It can be found inside a file src/AdvancedHelpManager.php, and looks like this:

class AdvancedHelpManager extends DefaultPluginManager {
  …

  /**
   * Search the system for all available help topics.
   * @todo check visibility of the method.
   */
  public function getTopics() {
    $ini = $this->parseHelp();
    return $ini['topics'];
  }
  …
}

I want to call it from my module, in order to get hold of the list of topics I expect it to return.

So far, I've tried:

$foo = new AdvancedHelpManager();
$bar = $foo->getTopics();

but this returns the error "Error: Class 'AdvancedHelpManager' not found.

I guess I need to put some sort of "use"-statement on top of the file I try to use it, to make the class visible, but I am currently unable to figure out what that statement should be.

1 Answer 1

1

Your current code doesn't work because of namespaces, but even so, that's not the right way to approach your requirement.

AdvancedHelpManager is a plugin manager, which is a service, so you should get the instance of it like so:

$plugin_manager = \Drupal::service('plugin.manager.advanced_help');
$topics = $plugin_manager->getTopics();

(as always, if you're in a context where DI is available, inject the service instead of calling the static \Drupal method).

If any of this doesn't make sense it would be a very good idea to read the Services and dependency injection docs, which help to explain the architecture behind Drupal 8.

2
  • 1
    Thanks a lot! I've spent the better part of the day trying to figure out that. I understand that D8 requires a completely different mindset compared to D7. Thanks for the reading recommendation! Jul 23, 2019 at 14:38
  • You're welcome. Yeah if you're coming from procedural PHP and D7, D8 can be pretty daunting, there are so many new concepts to learn. I found reading the change records really useful when I was getting in to D8, they're a good way to get a running explanation of what changed to what, and importantly why it changed
    – Clive
    Jul 23, 2019 at 18:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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