How to manage module dependencies with composer in Drupal 8

How to manage module dependencies with composer in Drupal 8

default avatar
VonJesus Olivas
April 09, 2015
FFW Blog - illustration

Composer is one of the greatest things that has happened to PHP lately.

Composer is a tool for dependency management in PHP. It allows you to declare the dependent libraries your project needs and it will install them in your project for you.

Thanks to Composer Manager a contributed module, we can now take advantage of this great tool while working with Drupal 8. 

I will list the required steps to include an external library within a Drupal 8 module and use Composer Manager to download them.

Requirements 

You will need to have Drush, Composer previously loaded and a Drupal 8 installation. In case you need some guide about with the requierements you can take a look a this blog post Try Drupal 8 now.

I will use the Drupal Console to create a new module, you can see use this link to learn how to Install Drupal Console globally.

Getting Composer Manager

[gist:9b7087053aebbd481193]

Creating a new Drupal 8 module.

[gist:490c402045449d56c510]

The generate:module command will create two files for you:

  • modules/custom/jolinotif/jolinotif.info.yml
  • modules/custom/jolinotif/jolinotif.module

Adding a third party library to module

For this particular example I will use https://github.com/jolicode/JoliNotif, this library will allow us to send desktop notifications from a PHP script.

I will create a composer .json file within the root directory at our new generated module.

[gist:25333dead7e7ba0b0403]

Make sure your new composer file is valid, you can check by running "composer validate" from module root directory.

Downloading the third party library

I will use composer to download the third party libraries defined on the composer.json file module executing "composer drupal-update" command form drupal core directory.

[gist:4aef1ce12039c8e6e00a]

Creating a Logger class

I will create a new file class "JolinotifLog.php" inside src/Logger directory.

[gist:43c1b61a36aac1771f2f]

Registering the logger class a service

I will create a new YAML file "jolinotif.services.yml" at module root directory. 

[gist:c729571d54a082b6a32b]

Make sure you add the "logger" tag name.

Screenshots:

Drupal 8 Composer Registering the Logger Class

Drupal 8 Welcome Screen

Drupal 8 Composer

Try this code

You can get this module code from https://github.com/jmolivas/jolinotif-drupal