35

In Drupal 7, you can use module_exists() to check whether a module is enabled (as well as whether it exists).

For example,

if (module_exists('devel')) {

How can you check whether a module is enabled in Drupal 8?

0

2 Answers 2

62

Just like Clive mention....

injecting the module_handlerservice would be preferable to using \Drupal (assuming it's an option in current context)

Here is an example of checking if a module is enabled using a service (without injecting it).

$moduleHandler = \Drupal::service('module_handler');
if ($moduleHandler->moduleExists('devel')) {
  // Code Here
}
3
  • 3
    \Drupal::moduleHandler ends up just making an equivalent call to get the "module_handler" service anyway (see the moduleHandler doco). The key word in Clives comment was injecting, i.e. passing the service to a constructor.
    – George
    Commented Apr 12, 2018 at 1:10
  • Even though this is not an injection, this code is probably the best you can have if running in a hook_update_nnn() function in your module's .install file, as there's no way of injecting services in a functional context. Commented Nov 16, 2020 at 7:11
  • This is exactly the same as the code shown from the other answer, which is preferable when the Drupal class has an helper method. If a hook is only using a service, I would not use injection; in the case the services are more than one, it's possible to write code that uses injection, via a class.
    – avpaderno
    Commented Nov 16, 2020 at 14:30
27

Like this:

  if (\Drupal::moduleHandler()->moduleExists('devel')) {
3
  • 3
    It's worth nothing that injecting the module_handler service would be preferable to using \Drupal (assuming it's an option in current context)
    – Clive
    Commented Jan 28, 2016 at 9:15
  • @Clive why is that preferable?
    – ryrye
    Commented Jan 8, 2020 at 19:13
  • 2
    @ryrye Because you can mock injections in tests, see drupal.org/docs/8/api/services-and-dependency-injection/… Commented Apr 30, 2020 at 9:26

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.