Skip to main content

PhpStorm live templates to automate the boring things

Published on

I finally took a look at writing a custom live template with PhpStorm. I've used them several times to automate scaffolding a foreach statement or other random suggestions that a Tab keypress leads to automated scaffolded code. But I never really dove in to see how they work or could be customized. Then, I had to fix some of my code to comply with Drupal's coding standards.

Drupal requires document comments for all methods, including a short comment. 

  • When a method overrides a method or implements one from an interface, you use {@inheritdoc}, which indicates that the documentation for the method should come from the parent definition.
  • For __construct, we used a pattern of Constructs a new $CLASS_NAME object. as our short comment

Most of the time, I skip these nuanced coding standards until I am happy with my code. Then I toil along copying, pasting, and manually adjusting. Finally, I got sick of it and decided to take 10 minutes to try and automate the dang thing.

To create a live template, you can follow the documentation or these quick steps:

  1. Open settings (CMD + , or Ctrl + Alt + S)
  2. Select Editor
  3. Select Live templates
  4. Click the + icon to add a template

The kicker was figuring out that you had to assign contexts for live templates. It took me a minute to notice the warning at the bottom of the user interface or the link to open the menu to select a context.

Live template for {@inheritdoc}

This one was pretty simple. For the abbreviation, I just used inheritdoc. And then for the template:

/**
 * {@inheritdoc}
 */

And then, for the contexts, I selected class members.

When typing code, I only need to type inheritdoc and press Tab to get my document block for the method.

Live template for __construct

Creating a live template to create __construct comment blocks requires configuring a variable for the template. The format I use is Constructs a new $CLASS_NAME object. We need $CLASS_NAME to be the value of the current class name.

I couldn't think of a good abbreviation, so I used cnsdoc as shorthand for "constructor" and "doc."

The template is:

/**
 * Constructs a new $CLASS_NAME$ object.
 */

Variables in live templates start and end with $. Once a template has a variable, the Edit Variables button becomes active. We have to define what $CLASS_NAME$ is derived from. The expression is phpClassName().

 

For the contexts, I selected class members.

Now, I can go to my __construct method and generate my comment block!

Here is the result:

I'm available for one-on-one consulting calls – click here to book a meeting with me 🗓️