写代码总绕不过须要调试,除了 UnitTest 外,咱们仍是须要借助 Xdebug 进行调试。php
因此今天来讲说如何基于本地 Docker 环境下,使用 Xdebug。html
这里的使用,是分别整合到 VS Code 和 PHPStorm 下。
仍是基于神级武器 —— Laradock。咱们先看看 Laradock 官网是怎么安装 Xdebug。nginx
Install xDebug#1 - First install xDebug in the Workspace and the PHP-FPM Containers: docker
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 truejson2 - Re-build the containers docker-compose build workspace php-fpmubuntu
咱们修改对应的地方,而后 build
,若是出现下面的错误提示:app
尝试添加国内源试试:php-fpm
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
查看安装状态:post
目前开发使用 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 https://intellij-support.jetbrains.com/hc/en-us/community/posts/360000229624-Setting-up-xDebug-with-PHPUnit-using-Docker-for-Mac-and-PHPStorm
- Laradock + XDebug + MS Code? No problem https://medium.com/full-stack-development/laradock-xdebug-ms-code-no-problem-35a4338deb3f
- Laradock的xdebug在vscode上使用的配置 https://www.itread01.com/content/1526278934.html
- 如何設定VSCode XDebug在laradock環境上 https://blog.scottchayaa.com/post/2018/10/16/vscode-phpunit-on-laradock/