Using PHPStorm's Live Templates

Saving keystrokes is not to be sniffed at when your fingertips and time are so precious. Fortunately, PHPStorm has a lovely feature which will allow you to use abbreviations for common code elements, called Live Templates. Fancy a look at what’s there? Let’s focus on PHP for this tutorial but as you will soon see, there are many other languages and options.

To begin, start by going to File > Settings or press Ctrl-Alt-S to bring the settings screen up.

Now click on Editor > Live Templates and expand the PHP section.

Quite a choice, right? Let’s play with one now. Open up a new PHP file in the IDE and type the following:

1
eco <tab>

As you can see, it expands that into:

1
echo "";

Even better, it places the cursor between the quotes. Pretty handy but not that impressive since you’ve only saved typing a few keystrokes. Let’s try a more useful one. Type:

1
2
3
class X {

}

Now add:

1
prif<tab>

inside the class. That will suddenly expand to:

1
2
3
4
5
6
class X {
private function ()
{

}
}

Much more useful. Can you start to imagine how much more free time with your loved ones you will generate by doing that several million times? The interesting thing to note is that the IDE is context aware. Try expanding that abbreviation outside of a class and it just won’t do anything. OK - I know what you are thinking: How do I get on the band wagon and create my own examples? As you might expect, this is pretty simple too so let’s implement something that is often done when brute-forcing debugging. We’re going to create an abbreviation for this:

1
2
var_dump($variable);
die();

With the PHP heading highlighted in the Live Templates settings, click on the green “+” symbol on the right. Now choose “1. Live Template”. In the area at the bottom, give your template an abbreviation name: vdd. This has to be something not already being used or that might interfere with PHPStorm’s helpful suggestions. Now add a description to the right. Now the magic. Inside “Template text”, add the following:

1
2
var_dump($END$);
die();

The $END part tells PHPStorm to leave the cursor at that point. We’re almost done. We just need to let PHPStorm know where this abbreviation is applicable (remember what I told you about the private function above?). Where it says No Applicable contexts at the bottom, click on Define. Expand PHP, then check “Statement”.

I can feel your excitement building - go on, now try out your template!


Hi! Did you find this useful or interesting? I have an email list coming soon, but in the meantime, if you ready anything you fancy chatting about, I would love to hear from you. You can contact me here or at stephen ‘at’ logicalmoon.com