推薦程式碼除錯工具 Xdebug

yzf01發表於2021-09-09

寫程式碼總繞不過需要除錯,除了 UnitTest 外,我們還是需要藉助 Xdebug 進行除錯。

所以今天來說說如何基於本地 Docker 環境下,使用 Xdebug。

這裡的使用,是分別整合到 VS Code 和 PHPStorm 下。

推薦程式碼除錯工具 Xdebug

安裝 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

參考:laradock.io/documentati…

我們修改對應的地方,然後 build,如果出現下面的錯誤提示:

推薦程式碼除錯工具 Xdebug

嘗試新增國內源試試:

RUN  sed -i s@/archive.ubuntu.com/@/mirrors.aliyun.com/@g /etc/apt/sources.list
複製程式碼

重新 docker-compose up -d nginx 後,在 Windows / Mac 下用命令 ./php-fpm/xdebug status 檢視安裝狀態:

mark

配置 Xdebug

目前開發使用 IDE,個人覺得普遍用的最多的就是 VS Code 和 PHPStorm。所以下面就利用這兩個 IDE,分別說說如何使用 Xdebug 的。

VS Code

在 VS Code 下,如果沒安裝 Xdebug 外掛,直接搜尋安裝即可:

mark

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

mark

這樣就會專案的 .vscode 資料夾下多了一個 Xdebug 配置檔案 launch.json,我們配置埠號與 php-fpm 下的 Xdebug 一致,我們再配置 pathMappingsdocker 下的專案路徑與本地專案路徑關聯。具體如下:

{
    "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,列印出如下內容,即表示等待請求:

推薦程式碼除錯工具 Xdebug

我們寫個 Demo,並設定斷點:

Artisan::command('hello', function () {
    $i = 0;
    $i++;

    return "hello".$i;
});
複製程式碼

推薦程式碼除錯工具 Xdebug

然後啟動 Xdebug,並執行命令:

php artisan hello
複製程式碼

我們可以看到很多輸入、輸出、斷點等資訊:

推薦程式碼除錯工具 Xdebug

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

推薦程式碼除錯工具 Xdebug

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

推薦程式碼除錯工具 Xdebug

推薦程式碼除錯工具 Xdebug

PHPStorm

在 Mac 或者 Windows 10 下 Docker 的預設 ip 為:10.0.75.1,

我們先增加一個 Server,其中:

  • Name:laradock
  • Host: 10.0.75.1
  • mappings,等同於上文 VS Code 配置的 pathMappings

推薦程式碼除錯工具 Xdebug

然後,可以新建 PHP Remote Debug,其中:

  • Server:關聯到我們上面建的 laradock
  • IDE key:和 Laradock‘s php-fpm 中配置的保持一致即可

推薦程式碼除錯工具 Xdebug

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

推薦程式碼除錯工具 Xdebug

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

推薦程式碼除錯工具 Xdebug

我們繼續往下走:

推薦程式碼除錯工具 Xdebug

總結

用好 Xdebug,更加直觀的瞭解方法中每個變數的動態變化,能提高我們跟蹤和排查程式碼的問題所在。至於下一步如何更好的使用 Xdebug,就看各自的實際專案和開發需要了。

參考

  1. Setting up xDebug with PHPUnit using Docker for Mac and PHPStorm intellij-support.jetbrains.com/hc/en-us/co…

  2. Laradock + XDebug + MS Code? No problem medium.com/full-stack-…

  3. Laradock的xdebug在vscode上使用的配置 www.itread01.com/content/152…

  4. 如何設定VSCode XDebug在laradock環境上 blog.scottchayaa.com/post/2018/1…

相關文章