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.
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.
- Get into the preferences pane for editing live templates by following these directions http://www.jetbrains.com/idea/webhelp/creating-and-editing-template-variables.html
- Find the "PHP" section.
- Click the "+" symbol. In my version (Ultimate 12, Darcula), the plus symbol is to the upper right in the preferences pane.
- Follow the instructions for naming listed in the IntelliJ docs linked above.
- Paste the code outlined below (Exhibit A) into the "Template Text" box.
- In the box below the template text, be sure to choose "PHP" as an applicable context
Exhibit A, the live template:
try { $SELECTION$ } catch (\Exception $$e) { $$this->logger->warn("$END$"); }
Now, when you want to use the template,
- Highlight the text you'd like to wrap in the try-catch
- Hit the keyboard combo for "Surround with Live Template"
- Hit Enter.
- IntelliJ will wrap the inject the template and replace "$SELECTION$" with the highlighted text.
- It will then place your cursor between the double quotes at "$END$"
- 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 =)
- 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.
Comments