亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

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

PHP: Skip the boring part & press Tab!

Dec 21, 2024 pm 07:41 PM

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 of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
PHP Variable Scope Explained PHP Variable Scope Explained Jul 17, 2025 am 04:16 AM

Common problems and solutions for PHP variable scope include: 1. The global variable cannot be accessed within the function, and it needs to be passed in using the global keyword or parameter; 2. The static variable is declared with static, and it is only initialized once and the value is maintained between multiple calls; 3. Hyperglobal variables such as $_GET and $_POST can be used directly in any scope, but you need to pay attention to safe filtering; 4. Anonymous functions need to introduce parent scope variables through the use keyword, and when modifying external variables, you need to pass a reference. Mastering these rules can help avoid errors and improve code stability.

How to handle File Uploads securely in PHP? How to handle File Uploads securely in PHP? Jul 08, 2025 am 02:37 AM

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

Commenting Out Code in PHP Commenting Out Code in PHP Jul 18, 2025 am 04:57 AM

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

How Do Generators Work in PHP? How Do Generators Work in PHP? Jul 11, 2025 am 03:12 AM

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

Tips for Writing PHP Comments Tips for Writing PHP Comments Jul 18, 2025 am 04:51 AM

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

How to access a character in a string by index in PHP How to access a character in a string by index in PHP Jul 12, 2025 am 03:15 AM

In PHP, you can use square brackets or curly braces to obtain string specific index characters, but square brackets are recommended; the index starts from 0, and the access outside the range returns a null value and cannot be assigned a value; mb_substr is required to handle multi-byte characters. For example: $str="hello";echo$str[0]; output h; and Chinese characters such as mb_substr($str,1,1) need to obtain the correct result; in actual applications, the length of the string should be checked before looping, dynamic strings need to be verified for validity, and multilingual projects recommend using multi-byte security functions uniformly.

Quick PHP Installation Tutorial Quick PHP Installation Tutorial Jul 18, 2025 am 04:52 AM

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre

Learning PHP: A Beginner's Guide Learning PHP: A Beginner's Guide Jul 18, 2025 am 04:54 AM

TolearnPHPeffectively,startbysettingupalocalserverenvironmentusingtoolslikeXAMPPandacodeeditorlikeVSCode.1)InstallXAMPPforApache,MySQL,andPHP.2)Useacodeeditorforsyntaxsupport.3)TestyoursetupwithasimplePHPfile.Next,learnPHPbasicsincludingvariables,ech

See all articles