Pantheon Community

Creating Custom Drupal 8 Modules

Hello! I am working to create my first custom Drupal 8 module, and wanted to see if anyone had tips or pitfalls they learned from. I have already watched several demos and tutorials about how to set one up but I wanted to know if there are any recommendations about best practices that people expect from the community? :slightly_smiling_face:

1 Like

I would recommend hitting the books on the following topics:

  • Symphony Containers
  • Dependency Injection in PHP
  • Symphony Services

A couple other tidbits, study up on the Entity API, learn to love the EntityTypeManager class, and also set up composer to manage your module dependencies.

Here are a couple links…
https://api.drupal.org/api/drupal/core!core.api.php/group/container/8.7.x
https://api.drupal.org/api/drupal/services/8.7.x

Here is a quick snippet of how to inject a Drupal service into your custom module class…

/**
 * {@inheritdoc}
 */
public static function create(ContainerInterface $container) {
  // Instantiates this form class.
  return new static(
    // Load the service required to construct this class.
    $container->get('current_user')
  );
}

To manage any dependencies you have within your modules via composer I use composer-merge-plugin

With this you can include packages for your module within a composer file in the module folder, and running composer install will install the dependencies in your root /vendor directory which I found very handy

Hope this helps.
Feel free to fire back with any specific questions as you make your way through your first module.
Good luck!

1 Like

I shared on the Slack channel, but here it is for others too. Drupalize.me was a very handy resource for the module development training but also for their excellent trainings on OO-PHP which was key. Agreed with @JBack about Dependency Injection - that is a totally new thing with D8 and well worth learning. Additionally, other key items include the new routing / menu system, how to attach libraries (CSS/JS), and the new configuration management stuff. And of course lots of debugging with Devel and Kint. I also took a class at BADCamp one year that was essentially a full-day training on module development for D8 and that really helped to solidify all that I had learned online.

I’ve found that when something is really stumping me, I create a dummy page in code with a dummy controller and essentially start dumping all of my tests there - like spitting out results of functions, services, etc. Eventually, I’ll remove that code, but it’s really handy for testing. And while it’s more in the theming system, I’ve used a lot of default twig templates for my custom modules as well so by learning how to use those, you have a ton of control over the output.

I hope this helps!

1 Like

Thank you both! I am going to look into these as I start putting together the concept.