What I Learned from Porting the Scanner Module

2019-05-02

Christian Crawford

What I Learned from Porting the Scanner Module

Lessons learned from porting Drupal 7 scanner module to Drupal 8 including plugin system, batch API, and TempStore.

Introduction

I was recently given a requirement by a client in which they wanted content authors to be able to find and replace instances of words across potentially every piece of content in the site. In Drupal 7 (D7) there is a module called scanner, which does exactly what they needed. Drupal 8 (D8) has been around for three and a half years at this point so I hoped that someone had gone through the effort of porting it. Unfortunately for me there was no such option for D8.

1. Don’t Reinvent the Wheel if You Don’t Have To

Before I wrote a single line of code I went into the issue queue and looked to see if anyone had either requested or even started on a port of the module. Someone had started the work and attached a patch. Following that I went and looked at how the old code worked so that I could get an idea of how the rest of the functionality should be achieved.

2. Don’t Be Afraid to Look for and Try Out New Ideas

With the introduction of Drupal 8 a lot of that confidence went away when I started looking at how vast and sprawling the API had become. Just like in D7, with each project you will learn new concepts and how/when to apply them.

In the case of the scanner module port, I learned quite a few new things:

  • How to write a brand new plugin and all it’s parts (plugin manager, plugin interface, annotation, and the plugins themselves)
  • How to use the Batch API
  • How to use the TempStore service to persist data across requests

3. Ask for Feedback from Your Peers

Once I got the find and replace functionality consistently working I did a demo and code walkthrough with one of my colleagues. Getting a second opinion almost always helps you either improve your code or at the very least deepens your understanding of your code as you explain it to another person.

Showing my code to others allowed me to improve the quality of my code and forced me to think in different ways.

4. Get in the Habit of Writing Small Chunks of Code and Testing Often

Often times we want to write a new module or plugin we get caught up with often writing the whole functionality before testing any of it. This is a bad habit which I have worked on over the past few years, and feel it has increased my productivity and efficiency greatly.

If I had sat down and written the search/replace/undo operations in one go without testing it, I would likely encounter a bunch of bugs in my code. If I instead simply write the search functionality, then the replacement function, and finally the undo operation, with testing after each of those steps debugging becomes much quicker and simpler.

For more details on the actual code you can read about it here.