简体   繁体   中英

Php format on save in Visual Studio Code

Can you format on save PHP as well with the Beautify extension of Visual Code ? If yes how do you set it up? If not which extension does that?

You can use the vscode-php-formatter extension which will format your PHP code either on demand (via key binding) or on save.

It's a wrapper for this PHP Coding Standards Fixer , which as you can see allows for pretty flexible configuration, so you can adjust it to your tastes.

To add custom configuration, create a .php_cs file, add this to your argument settings:

phpformatter.arguments: ["--custom-config=/path/to/file/config.php_cs"]

And create a file with your custom rules:

<?php
$finder = Symfony\Component\Finder\Finder::create()
    ->files()
    ->in(__DIR__)
    ->exclude('vendor')
    ->exclude('resources/views')
    ->exclude('storage')
    ->exclude('public')
    ->notName("*.txt")
    ->ignoreDotFiles(true)
    ->ignoreVCS(true);

$fixers = [
    '-psr0',
    '-php_closing_tag',
    'blankline_after_open_tag',
    // more custom rules
];

return Symfony\CS\Config\Config::create()
    ->level(Symfony\CS\FixerInterface::PSR2_LEVEL)
    ->fixers($fixers)
    ->finder($finder)
    ->setUsingCache(true);

Read more at the source

Elaborating on Zain's answer, I'm writing PHP and React and want to auto format both.

First install "PHP Intelephense" extension to format PHP and the "Prettier" extension to format JS. Then open VS Studio Code's settings and:

  1. click the icon in the top right corner to edit as JSON
  2. Remove any generic default formatter setting
  3. Add JavaScript and React formatter settings
  4. Add PHP formatter setting
  5. Save

分步说明

Try plugin PHP Intelephense by Ben Mewburn. As the manual says:

Lossless PSR-12 compatible document/range formatting. Formats combined HTML/PHP/JS/CSS files too.

The capitalized '[PHP]' did not work for me. However, the lowercase did. Like this:

"[php]": {
    "editor.defaultFormatter": "bmewburn.vscode-intelephense-client"
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM