Home >Backend Development >PHP Tutorial >PHP: Skip the boring part & press Tab!

PHP: Skip the boring part & press Tab!

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-21 19:41:14715browse

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:

PHP: Skip the boring part & press Tab!

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:

PHP: Skip the boring part & press Tab!

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:

PHP: Skip the boring part & press Tab!

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:

PHP: Skip the boring part & press Tab!

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 ()
{

}

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

PHP: Skip the boring part & 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:

PHP: Skip the boring part & press Tab!

You'll get something like the following:

PHP: Skip the boring part & press Tab!

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):

PHP: Skip the boring part & press Tab!

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:

public static function ()
{

}

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:

public static function ()
{

}

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?

PHP: Skip the boring part & press Tab!

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:

PHP: Skip the boring part & press Tab!

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="over" value="#[\Override]" description="add override attribute" toReformat="true" toShortenFQNames="true">
  <context>
    <option name="PHP" value="true" />
  </context>
</template>

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:

PHP: Skip the boring part & press Tab!

? 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 ?

The above is the detailed content of PHP: Skip the boring part & press Tab!. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn