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?
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?
Just like Clive mention....
injecting the
module_handler
service 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
}
\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.
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.
Like this:
if (\Drupal::moduleHandler()->moduleExists('devel')) {
module_handler
service would be preferable to using \Drupal
(assuming it's an option in current context)