Logo

dev-resources.site

for different kinds of informations.

PHP: Skip the boring part & press Tab!

Published at
12/17/2024
Categories
beginners
ide
php
productivity
Author
spo0q
Categories
4 categories in total
beginners
open
ide
open
php
open
productivity
open
Author
5 person written this
spo0q
open
PHP: Skip the boring part & press Tab!

Phpstorm is a fantastic IDE for PHP developers. While it's not free, you get pretty cool features, such as Live Templates.

🤓 Type fore and tab

Live Templates are customizable expands for your editor.

PhpStorm already has helpful expands for various contexts, including PHP, by default.

You can check it in Settings > Editor > Live Templates:

fore removes the hassle of typing foreach loops manually.

If you type f, fo, or for, you may get fore in the list, but ensure you select fore and not foreach, which won't do magic here:

Typing fore is a bit longer but safer to get the desired template. It should also have a description (foreach iterable_expr as $value).

The Live Template allows customizing the name of the variables conveniently:

Then, just press ⇥Tab to expand the whole foreach block.

N.B.: I use the mouse in the demo but the idea is to stick with the keyboard.

📁 Live Templates are contextual

Context allows better organization and reduces noise in the editor.

For example, you don't need the fore expand to edit HTML files.

That's why this live template is only applicable for PHP:

You can make custom template groups, apply a Live Template to one or several groups, and define custom variables to control the render.

You can even define how to expand the template with the keyboard (e.g, tab vs. enter vs. space).

☄️ Enjoy default templates

Instead of typing the same constructs again and again:

public static function ()
{

}
Enter fullscreen mode Exit fullscreen mode

Just type pu or pub, select the pubsf Live Template and press ⇥Tab:

Source: Official documentation - Live templates

🛠️ Making custom expand

You can create custom Live Templates to fit your needs.

Go to Settings > Editor > Live Templates, select the PHP template group and press the + button to add a new Live Template:

You'll get something like the following:

Pay extra attention to the checkbox called applicable context (here, "PHP statement").

If you don't see your live template in the editor, it's probably because you forgot to configure something or your case doesn't match any of the checked items.

You get advanced granularity with this setting, so change the applicable context accordingly to make your expand work.

👣 Hello world: Add your first template

Let's add a live template to add the override attribute (PHP 8.3), which is meant to trigger an error if a method explicitly overrides its parent while the parent class does not have that method (any more):

Now, when you type over in your editor, you get the override attribute, which removes the hassle of writing it manually.

PhpStorm saves it using XML:

<template name="over" value="#[\Override]" description="add override attribute" toReformat="true" toShortenFQNames="true">
  <context>
    <option name="PHP" value="true" />
  </context>
</template>
Enter fullscreen mode Exit fullscreen mode

Leverage predefined variables

While it's not an exhaustive list, these predefined variable are important:

Variable Description
$END$ Caret position after editing variables
$SELECTION$ Denotes the code fragment to be wrapped in surround templates
$RETURN_TYPE$ Return type of the function or method

Source: documentation - predefined variables

$SELECTION$ is meant for more advanced usages. It's required to create surround templates:

try {
    $SELECTION$
} catch ($TYPE$ $$$VARIABLENAME$) {
    Logger::log($$$VARIABLENAME$);
    $END$
}
Enter fullscreen mode Exit fullscreen mode

N.B.: Please read the documentation to configure your surround template correctly (you have to edit variables).

Add your own variables

Remember the $item variable we've just saw with fore?

Pretty convenient to modify the name on the fly, isn't it?

To understand how it works, just edit template variables and check the associated expression:

Built-in expressions allow pretty advanced customization, such as smart autocomplete, name suggestion, and even regular expressions.

Duplicate existing templates

You can right click on any Live Template in the list to copy it. If you inspect the clipboard, you'll see something similar to the following XML:

<template name="fun" value="function $NAME$($PARAMETERS$){&#10;    $END$&#10;}" description="function" toReformat="true" toShortenFQNames="true">
  <variable name="NAME" expression="" defaultValue="" alwaysStopAt="true" />
  <variable name="PARAMETERS" expression="phpVar" defaultValue="" alwaysStopAt="true" />
  <context />
</template>
Enter fullscreen mode Exit fullscreen mode

It can be useful to start a new Live Template from an existing one.

However, you'd rather use the duplicate button (at the right of the delete button "-") in this case:

👥 Share your templates

PhpStorm stores Live Templates as XML files in the templates directory of the IDE configuration directory: see idea.config.path.

Copy-paste might be fine, but you may want to synchronize those snippets instead. For example, if you maintain and share common templates for all team members.

You can also export and import all live templates manually.

N.B.: Please read this section for the setup.

😏 I don't need that. I have AI.

You may use AI tools or enable the JetBrain AI assistant (plugin), so the IDE can make predictions based on your usage.

Please read the privacy policy before anything, though:

The JetBrains AI Service can collect two types of data related to the usage of AI features: behavioral and detailed data. Both of these types of data collection are fully controlled by the user.

The data from JetBrains AI Service is sent to third-party language model providers

I totally get the hype around AI, and it does a great job with repetitive tasks.

In my experience so far, live templates are more consistent and not prone to hallucinations, though.

Note that it does not mean you cannot combine these tools, but please double-check AI suggestions before pressing ⇥Tab.

🎨 Be creative

Here are some use cases for live templates (PHP):

  • loops and common constructs in various languages
  • surround blocks (e.g., custom try/catch)
  • boilerplate for data provider (PHPUnit)
  • boilerplate for test methods
  • phpdoc that contains specific keywords (e.g., @test, @dataprovider)

✅ Pros

  • highly customizable (focus on the domain)
  • spare literally dozens of clicks
  • default Live Templates rock!
  • only apply to specific contexts (Template groups)

❌ Cons

  • the syntax to write variables can be messy, especially in surround templates (e.g., $$$VARIABLENAME$)
  • templates can be redundant if you don't use template groups or reinvent the default ones

Wrap up

This feature is a bit underrated, even by dev teams that use PhpStorm daily.

Enjoy live templating and press ⇥Tab 🚀

ide Article's
30 articles in total
Favicon
Remove plugins affecting Intellij idea
Favicon
A Card-Based Approach to Mobile-First IDE
Favicon
PHP: Skip the boring part & press Tab!
Favicon
Amazon Q Developer: The AI-Powered Code Companion You’ve Been Waiting For
Favicon
Preparando o ambiente de desenvolvimento da melhor API de tabelas de campeonato que você já viu!
Favicon
Tools I use in software engineering
Favicon
Plugin Release GitLab Master Plugin - Enhance Your GitLab Experience in IntelliJ IDEA
Favicon
Windsurf was Indeed Better Than Cursor IDE – t3.gg is biased
Favicon
Mine 14 dage med Cursor
Favicon
Why JetBrains IDEs Are Better Than VS Code for Developers
Favicon
Boosting Developer Efficiency with Cursor IDE: A Comprehensive Tool for Modern Coding
Favicon
Whoever Said You Need An IDE To Program In C?
Favicon
Incredibly Useful WireMock with IntelliJ IDEA
Favicon
How to use AI for coding the right way
Favicon
How To Use Xcode for Windows To Build iOS Apps
Favicon
🚨 Google Unveils Project IDX, a Game-Changer for App Development 🚨
Favicon
Use Android Studio Online || React Native Online Mobile View without Android Studio Using Google IDX
Favicon
Migrating a project from Visual studio to Rider
Favicon
Flutter's Essential Toolkit: Top Tools for Every Developer
Favicon
From Text Editors to Cloud-based IDEs - a DevEx journey
Favicon
A Tour of the Couchbase JetBrains Plugin for Developers
Favicon
Project IDX: Google's Cloud-Based Experiment in Streamlining Development
Favicon
Astro vs Visual Studio 2022 as Static Site Generators
Favicon
The Best IDEs for Java Development: A Comparative Analysis
Favicon
Full Line Code Completion by JetBrains: A Game-Changer for Secure, AI-Assisted Coding
Favicon
The project IDX
Favicon
Plugin: Análise de Vulnerabilidade
Favicon
Selecting Your LIGHTWEIGHT Python IDE
Favicon
The Dream Dies: Why Cloud IDEs Failed Developers
Favicon
A IDE do desenvolvedor do futuro 🔮

Featured ones: