Thursday, July 25, 2013

Add Try-Catch Block in IntelliJ for PHP Using Live Templates

Choosing a powerful IDE and investing the time to learn its many features is a distinctly rewarding experience, saving you countless hours of typing of and brain cycles on boiler plate code.

I find the "Live Templates" feature of IntelliJ to be a major time saver. Today, I wanted to add a missing template for PHP: "try catch." I read through the docs and wasn't immediately educated on how it worked. I had to mess around a bit to get it working and thought I'd share my findings.

  1. Get into the preferences pane for editing live templates by following these directions
  2. Find the "PHP" section.
  3. Click the "+" symbol. In my version (Ultimate 12, Darcula), the plus symbol is to the upper right in the preferences pane.
  4. Follow the instructions for naming listed in the IntelliJ docs linked above.
  5. Paste the code outlined below (Exhibit A) into the "Template Text" box.
  6. In the box below the template text, be sure to choose "PHP" as an applicable context
Exhibit A, the live template:

catch (\Exception $$e)

Now, when you want to use the template,

  1. Highlight the text you'd like to wrap in the try-catch
  2. Hit the keyboard combo for "Surround with Live Template"
  3. Hit Enter.
    1. IntelliJ will wrap the inject the template and replace "$SELECTION$" with the highlighted text.
    2. It will then place your cursor between the double quotes at "$END$"
    3. There is a way to have it stop along the way at "Exception" and "$e" allowing you to change the defaults, but I haven't gotten there yet =)
  4. Start typing your log message. If you don't typically have a $logger field defined in your class, you can customize this to fit your pattern.