# PHP 程式碼命名風格
本篇是筆記性質,盡量以簡短方式來協助記憶。
賺口飯吃以來,PHP 也寫超過四年了,我終於動工啦。
不過昨日查詢了一下 Google Trends PHP/Laravel/Vue/React/Python,
PHP 近年來明顯下滑,抖;台中在各種關鍵詞搜尋偏好第一名呢!
# 開發環境
- 編輯器:VSCode
- 編輯器擴充套件:phpfmt, phpcs, php DocBlocker
# PHP Standards Recommendations (PSR)
PSR 是由 PHP-FIG 提出來的 PHP 標準建議, 團隊遵循標準開發在交流上會比較容易,使用工具檢測程式碼也比較方便。
# PSR-1: Basic Coding Standard (opens new window)
注意 Side Effects
The phrase “side effects” means execution of logic not directly related to declaring classes, functions, constants, etc., merely from including the file.
Properties 並沒定義用哪種形式,但個人建議使用 $camelCase
# PSR-2: Coding Style Guide
PSR-2 於 2019-08-10 已經不推薦使用了 見 PSR-12
# PSR-3: Logger Interface (opens new window)
- 使用 monolog 時來查 PSR 定義的 log 等級
- 不一定會全用到,使用時要規劃一下
# PSR-4: Autoloader (opens new window)
- 注意!composer 2 對 PSR-4 有嚴格要求
# PSR-6: Caching Interface (opens new window)
- 寫 Redis Cache 時沒遵守,下次跟進
# PSR-7: HTTP message interfaces (opens new window)
- 如果你使用框架,只要記得實作 PSR-7 的 Interface 就好
- 或自己在原生中寫個小小的 MVC
# PSR-12: Coding Style Guide (opens new window)
- The
var
keyword MUST NOT be used to declare a property. - function name 採用 camelCase
- The keyword
elseif
SHOULD be used instead of else if so that all control keywords look like single words.
Switch
- There MUST be a comment such as
// no break
when fall-through is intentional in a non-empty case body.
# 經驗談
實際在開發時會遇到很多眉眉角角,一中都能各表,一套原則沒辦法套用到所有細節。
可能會因為接手專案、專案人事異動、又或是今天的我已不再是昨天的我,
細節像是大小寫,變數命名想法上會有改變,特此紀錄。
像是 PSR-1 中提到 Properties,重點是保持一致性
多人合作專案,分工很獨立的部分個人是遵循 PSR 規則
好處是有遵循規則,自己不用煩惱
手邊工具就可以做 lint 與 cs-fix
缺點是 N 個人就有大於 N 種風格
另外若協作開發同一部分,會造成 git diff 有許多 styles 的異動變數名稱無嚴格限制
想法一:Local var (in function/method) with camel_case
Global var (parameter/pass-by-reference) camelCase
想法二:一致 camelCase體驗後是偏好二,因為定義不清楚,不需要花心思去判斷上述的 Local/Global
# 參考
PHP Standards Recommendations - PHP-FIG (opens new window)
PHP7 開發之道其他章節還提到了
抽象類別的應用;如何拆抽象類別
依賴注入(實現 SOLID 的 DIP)