推薦程式碼除錯工具 Xdebug
寫程式碼總繞不過需要除錯,除了 UnitTest 外,我們還是需要藉助 Xdebug 進行除錯。
所以今天來說說如何基於本地 Docker 環境下,使用 Xdebug。
這裡的使用,是分別整合到 VS Code 和 PHPStorm 下。

安裝 Xdebug
還是基於神級武器 —— Laradock。我們先看看 Laradock 官網是怎麼安裝 Xdebug。
Install xDebug#
1 - First install xDebug in the Workspace and the PHP-FPM Containers:
a) open the .env file b) search for the WORKSPACE_INSTALL_XDEBUG argument under the Workspace Container c) set it to true d) search for the PHP_FPM_INSTALL_XDEBUG argument under the PHP-FPM Container e) set it to true
2 - Re-build the containers docker-compose build workspace php-fpm
參考: ofollow,noindex">laradock.io/documentati…
我們修改對應的地方,然後 build
,如果出現下面的錯誤提示:

嘗試新增國內源試試:
RUNsed -i s@/archive.ubuntu.com/@/mirrors.aliyun.com/@g /etc/apt/sources.list 複製程式碼
重新 docker-compose up -d nginx
後,在 Windows / Mac 下用命令 ./php-fpm/xdebug status
檢視安裝狀態:

配置 Xdebug
目前開發使用 IDE,個人覺得普遍用的最多的就是 VS Code 和 PHPStorm。所以下面就利用這兩個 IDE,分別說說如何使用 Xdebug 的。
VS Code
在 VS Code 下,如果沒安裝 Xdebug 外掛,直接搜尋安裝即可:

安裝後,增加 Xdebug 環境配置:

這樣就會專案的 .vscode
資料夾下多了一個 Xdebug 配置檔案 launch.json
,我們配置埠號與 php-fpm
下的 Xdebug
一致,我們再配置 pathMappings
讓 docker
下的專案路徑與本地專案路徑關聯。具體如下:
{ "version": "0.2.0", "configurations": [ { "name": "XDebug listening to Laradock", "log": true, "type": "php", "request": "launch", "port": 9000, "pathMappings": { "/var/www/myrss": "${workspaceFolder}", } }, { "name": "Launch currently open script", "type": "php", "request": "launch", "program": "${file}", "cwd": "${fileDirname}", "port": 9000 } ] } 複製程式碼
好了,我們啟動 XDebug
,打印出如下內容,即表示等待請求:

我們寫個 Demo,並設定斷點:
Artisan::command('hello', function () { $i = 0; $i++; return "hello".$i; }); 複製程式碼

然後啟動 Xdebug
,並執行命令:
php artisan hello 複製程式碼
我們可以看到很多輸入、輸出、斷點等資訊:

其中我們也能看到此時的變數 $i
處於未初始狀態:

我們在這斷點繼續往下執行:


PHPStorm
在 Mac 或者 Windows 10 下 Docker 的預設 ip 為:10.0.75.1,
我們先增加一個 Server,其中:
- Name:laradock
- Host: 10.0.75.1
- mappings,等同於上文 VS Code 配置的 pathMappings

然後,可以新建 PHP Remote Debug,其中:
- Server:關聯到我們上面建的 laradock
- IDE key:和 Laradock‘s php-fpm 中配置的保持一致即可

好了,我們可以使用 demo,建立斷點,執行 Debug 等待請求::

一樣的,執行命令: php artisan hello
:

我們繼續往下走:
