Adding a new module dependency

When in the course of feature development you need to add a module as a dependency, for example adding Video Embed Field module to Drutopia Core, we also need to ensure that this required module is enabled on sites that already have the feature module installed.

We do this by adding an update hook to the Drutopia feature module.

This means you may need to add a .install file to the feature module where there wasn’t one befere.

Here is the full drutopia_core.install file for the drutopia_core module:

<?php

/**
 * @file
 * Contains install and update functions for Drutopia Resources.
 */

/**
 * Enable dependent module Video Embed Field.
 */
function drutopia_core_update_8101() {
  \Drupal::service('module_installer')->install(['video_embed_field']);
}

Note that if you were adding this module as a dependency to another Drutopia feature module (such as drutopia_group) your update hook would be named differently (drutopia_group_update_8101()) but would otherwise be the same. Ensure your update hook is numbered to be the last in the .install file you are editing.

If you have multiple modules to enable you could provide them to the function as ['video_embed_field', 'another_module'].

All standard procedures for adding a dependency to a module still apply. Namely, add the module to both the .info.yml file and the composer.json file of the feature module:

Here is drutopia_core.info.yml with other dependencies removed for brevity:

name: 'Drutopia Core'
description: 'Provides core components required by other features.'
type: module
core: 8.x
dependencies:
  - video_embed_field
package: Drutopia

And here is the composer.json for drutopia_core, again with extraneous details removed:

{
  "name": "drupal/drutopia_core",
  "description": "Drutopia core is a base feature providing core components required by other features.",
  "type": "drupal-module",
  "require": {
    "drupal/core": "^8.6",
    "drupal/video_embed_field": "^2.0"
  }
}

We must do this for feature modules with beta or full releases, but there’s nothing stopping us from doing this for feature modules with alpha releases or even just in dev— existing update hooks are ignored when a module is installed, and won’t ever be run. Therefore, adding update hooks for new dependencies is best practice for in-development features.