DEV Community

Dhimas Kirana
Dhimas Kirana

Posted on

Prettier for PHP File Formats in VSCode

Hello, dev πŸ‘‹

If you are a programmer in the PHP language, of course, you want to make your coding look neat so that it is easy for other programmers to read. In VS Code there is an extension to automatically tidy up coding called Prettier.

But it turns out that by default Prettier does not support PHP formatting language. Although there is a PHP plugin for Prettier created by the community. You can just read the Use section on the GitHub page to see how to use the plugin together with Prettier to format the PHP language. In my opinion, this method is quite complicated because it would be easier if the formatting was executed when the PHP file was saved (formatOnSave).

PHP Intelephense

To format the PHP language, I suggest you use the VSCode extension called PHP Intelephense which was created by Ben Mewburn. Install the extension first.

After the extension is installed, you can go to File -> Preferences -> Settings, then look for "default formatter"

VSCode Default Formatter

Then change the Default Formatter to PHP Intelephense. Still in settings, look for "formatonsave" and then check Format On Save so that our PHP file is formatted automatically when saving the file.

Multiple Formatter

Now this becomes confusing when we also work in languages other than PHP, such as Javascript, Typescript, or other programming languages.

When we choose the Default Formatter to PHP Intelephense, this means that all files will be formatted using PHP Intelephense, while this extension only supports PHP. Then, how?

The solution is to use the settings.json configuration file in VSCode to set the PHP language using PHP Intelephense.

Now go to settings and change Default Formatter to Prettier. Why Prettier? Prettier itself supports quite a lot of languages such as JavaScript, TypeScript, JSX, Angular, Vue, CSS, HTML, JSON, GraphQL, and others.

Then you create settings.json using Ctrl + Shift + P then search for "open user settings". Select the (JSON) one. Then the settings.json file will open. So here add the following configuration:

"[php]": {
    "editor.defaultFormatter": "bmewburn.vscode-intelephense-client"
}
Enter fullscreen mode Exit fullscreen mode

This means that all files with the .php extension will be formatted using the PHP Intelephense extension. Don’t forget to save the settings.json.

Good luck 🍻

Top comments (0)