寫代碼總繞不過須要調試,除了 UnitTest 外,咱們仍是須要藉助 Xdebug 進行調試。php
因此今天來講說如何基於本地 Docker 環境下,使用 Xdebug。html
這裏的使用,是分別整合到 VS Code 和 PHPStorm 下。nginx
仍是基於神級武器 —— Laradock。咱們先看看 Laradock 官網是怎麼安裝 Xdebug。docker
Install xDebug#json
1 - First install xDebug in the Workspace and the PHP-FPM Containers:ubuntu
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 truebash
2 - Re-build the containers docker-compose build workspace php-fpmapp
參考:laradock.io/documentati…php-fpm
咱們修改對應的地方,而後 build
,若是出現下面的錯誤提示:post
嘗試添加國內源試試:
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
查看安裝狀態:
目前開發使用 IDE,我的以爲廣泛用的最多的就是 VS Code 和 PHPStorm。因此下面就利用這兩個 IDE,分別說說如何使用 Xdebug 的。
在 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
處於未初始狀態:
咱們在這斷點繼續往下執行:
在 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
:
咱們繼續往下走:
用好 Xdebug,更加直觀的瞭解方法中每一個變量的動態變化,能提升咱們跟蹤和排查代碼的問題所在。至於下一步如何更好的使用 Xdebug,就看各自的實際項目和開發須要了。
參考
Setting up xDebug with PHPUnit using Docker for Mac and PHPStorm intellij-support.jetbrains.com/hc/en-us/co…
Laradock + XDebug + MS Code? No problem medium.com/full-stack-…
Laradock的xdebug在vscode上使用的配置 www.itread01.com/content/152…
如何設定VSCode XDebug在laradock環境上 blog.scottchayaa.com/post/2018/1…