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 ofConstructs 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:
- Open settings (
CMD + ,
orCtrl + Alt + S
) - Select Editor
- Select Live templates
- 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:
Want more? Sign up for my weekly newsletter