Using Prettier to format PHP code in VS Code
Overview
Prettier is an opinionated code formatter that enforces consistent code style by parsing your code and re-printing it with its own rules. It automatically handles line length, indentation, and formatting decisions, eliminating debates about code style in development teams.
By default, Prettier supports languages such as JavaScript, TypeScript, HTML, Vue, CSS, SCSS, JSON, Markdown, and many others. However, PHP is not included in the core supported languages.
Fortunately, the community has created @prettier/plugin-php
, a plugin that brings Prettier's formatting capabilities to PHP code. This plugin allows you to maintain consistent PHP code formatting across your projects using the same tool you use for other languages.
Requirements
Before starting, ensure you have:
- Node.js installed (version 14 or higher recommended)
- VS Code with the official Prettier extension installed
Installation
Install the required packages in your project directory:
npm install --save-dev prettier @prettier/plugin-php
Note: The plugin requires PHP to be installed on your system as it uses PHP's built-in tokenizer for parsing.
VS Code Integration Setup
Step 1: Install Prettier Extension
Install the official Prettier - Code formatter extension from the VS Code marketplace.
Step 2: Configure Document Selectors
VS Code may not automatically recognize PHP files for Prettier formatting. Add PHP to your document selectors by updating your VS Code settings.json
:
{
"prettier.documentSelectors": [
"**/*.{js,jsx,ts,tsx,vue,html,css,scss,less,json,md,mdx,graphql,yaml,yml,php}"
]
}
Step 3: Set Prettier as the default formatter for PHP files
Add Prettier as the default formatter for PHP in your VS Code settings.json
:
"[php]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
}
Step 4: Create Prettier Configuration
Create a .prettierrc
file in your project root directory:
Basic Configuration:
{
"plugins": ["@prettier/plugin-php"]
}
Advanced Configuration:
{
"plugins": ["@prettier/plugin-php"],
"phpVersion": "8.2",
"printWidth": 100,
"tabWidth": 4,
"useTabs": false,
"singleQuote": true,
"trailingCommaPHP": true,
"braceStyle": "per-cs"
}
Note: All available config options can be found on their GitHub page.
Step 5: Format on Save options
Enable automatic formatting by adding to your VS Code settings:
{
"[php]": {
"editor.formatOnSave": true,
"editor.formatOnPaste": true
}
}
Conclusion
Using Prettier to format PHP code in VS Code provides several benefits:
- Consistency across multiple languages in your project
- Team standardization with shared configuration
- Automated formatting reducing manual code style decisions
- Integration with existing Prettier workflows
The @prettier/plugin-php
plugin makes it easy to extend your existing Prettier setup to include PHP files, maintaining the same formatting experience across your entire codebase.