确保已安装PhpStorm(可从官网下载CentOS兼容版本)及PHP环境(通过sudo yum install php php-cli php-devel php-mbstring php-xml
等命令安装依赖)。
Ctrl+Alt+L
(CentOS系统默认快捷键),即可自动格式化当前文件或选中部分。Code
→Reformat Code
(格式化整个文件)或Code
→Reformat Selection
(格式化选中代码块)。若需调整缩进、空格、换行等规则,可通过以下步骤配置:
打开File
→Settings
(或Ctrl+Alt+S
),展开Editor
→Code Style
→PHP
,在右侧面板中修改对应选项:
Tab size
(制表符大小)和Indent
(缩进空格数,如4);Spaces
选项卡中,勾选操作符前后、逗号后等位置是否添加空格;Wrapping and Braces
选项卡中,设置大括号位置(如Next line
)、等号对齐等规则。Apply
→OK
保存设置。PHP_CodeSniffer用于检测代码是否符合编码标准(如PSR2),PhpStorm可集成该工具:
打开File
→Settings
→Languages & Frameworks
→PHP
→Code Sniffer
,在Default Standard
下拉菜单中选择编码标准(如PSR2
),点击OK
保存。此后使用Reformat Code
时,PhpStorm会根据该标准格式化代码。
PHP-CS-Fixer可自动修复代码格式问题,需先全局安装:
在终端运行composer global require friendsofphp/php-cs-fixer
,并将Composer的vendor目录添加到环境变量(如编辑~/.bashrc
或~/.zshrc
,添加export PATH="$HOME/.composer/vendor/bin:$PATH"
,然后运行source ~/.bashrc
)。
接着在PhpStorm中配置File Watcher:
打开File
→Settings
→Tools
→File Watchers
,点击+
→Create File Watcher
,设置:
Program
:php
(系统PHP路径);Arguments
:fix $FileName$
(格式化当前文件);Output paths
:$FileNameWithoutExtension$.fixed
(格式化后文件路径)。若需在保存文件时自动格式化,可开启Save Actions
功能:
打开File
→Settings
→Tools
→Actions on Save
,勾选Reformat code
,点击OK
。此后每次保存PHP文件时,PhpStorm都会自动格式化代码。
以上步骤覆盖了CentOS系统中PhpStorm代码格式化的基础操作与进阶配置,可根据团队规范或个人习惯选择合适的方式。