PHP標準化之路(一):使用 EditorConfig 實現語法統一
EditorConfig 有助於為跨越各種編輯器和 IDE 的同一專案的多個開發人員維護一致的編碼樣式。 EditorConfig 專案由用於定義編碼樣式的檔案格式和一組文字編輯器外掛組成,這些外掛使編輯器能夠讀取檔案格式並遵循定義的樣式。 EditorConfig 檔案易於閱讀並且可以與版本控制系統配合使用。
因此在團隊專案裡,我們可以用 EditorConfig 實現編碼風格統一。除了 WordPress、Laravel、Symfony 等大型框架有自成一套的編碼規範以外,我建議所有的 PHP 專案都應該遵循PSR
PHP 標準規範。目前 PSR 中與編碼規範有關的專案有已定稿的 PSR-1 和 PSR-2,將來還會有正在草稿階段的 PSR-12。現在我們只需要按照 PSR-2 來執行就可以了。在專案裡我們可以在根目錄建立一個.editorconfig
檔案,內容如下:
# This file is for unifying the coding style for different editors and IDEs # editorconfig.org # PHP PSR-2 Coding Standards # http://www.php-fig.org/psr/psr-2/ root = true [*.php] charset = utf-8 end_of_line = lf insert_final_newline = true trim_trailing_whitespace = true indent_style = space indent_size = 4
然後到EditorConfig 官網現在對應的 IDE 外掛即可。如果你開發的是類似 Laravel 的包含多種語言的專案,可以參考下面的設定,對各種型別的檔案單獨設定編碼規則。
# EditorConfig is awesome: http://EditorConfig.org # top-most EditorConfig file root = true # All PHP files MUST use the Unix LF (linefeed) line ending. # Code MUST use an indent of 4 spaces, and MUST NOT use tabs for indenting. # All PHP files MUST end with a single blank line. # There MUST NOT be trailing whitespace at the end of non-blank lines. [*] charset = utf-8 end_of_line = lf insert_final_newline = true trim_trailing_whitespace = true indent_style = space # PHP-Files, Composer.json, MD-Files [{*.php,composer.json,*.md}] indent_size = 4 # HTML-Files LESS-Files SASS-Files CSS-Files JS-Files JSON-Files [{*.html,*.less,*.sass,*.css,*.js,*.json}] indent_size = 4 [*.vue] # Gitlab-CI, Travis-CI [*.yml] indent_style = space indent_size = 2