xdebug 调试
原理大致就是上图,具体可自行阅读 http://xdebug.org.cn/docs/remote ,这里不多说。
这里实际操作一下如何配置 xdebug,并且介绍几个调试技巧。
配置 xdebug 远程调试
1. 准备工作
新建一个项目 xdebug_demo,新建 public 目录,建一个 index.php,写一个 for 循环。
使用 docker,让项目跑起来。
docker run -d --name myweb -p 8086:80 -p 3309:3306 -v $(pwd):/var/www/html/app laraedit/laraedit
2. 服务端配置
docker exec -it myweb /bin/bash
进到 docker 里,确认已经安装了 xdebug
扩展。
开始配置。
vim /etc/php/7.0/fpm/conf.d/20-xdebug.ini
增加以下配置:
zend_extension=xdebug.so
xdebug.remote_enable = on
xdebug.remote_host = 192.168.22.125
# xdebug.remote_host = docker.for.mac.localhost # 也可用 docker.for.mac.localhost 替代 ip
xdebug.remote_autostart = 1
xdebug.remote_port = 9001
xdebug.remote_log = /home/tmp/xdebug.log
其中 192.168.22.125
是我主机的 ip。
改完重启 fpm。
/etc/init.d/php7.0-fpm restart
3. IDE 配置
服务端配置完了,再来配置 IDE,只需要修改监听的端口号。
修改完之后,打开绿色小电话,浏览器再访问一次 http://localhost:8086/ 即可 debug 了。
4. Cli 模式调试
在 docker 里执行以下命令设置 debug 相关环境变量。
export XDEBUG_CONFIG="remote_enable=1 remote_mode=req remote_port=9001 remote_host=192.168.22.125 remote_connect_back=0"
在 /var/www/html/app
目录下执行:
php public/index.php
断点成功。
如果出现如下错误,
执行一下 export PHP_IDE_CONFIG="serverName=SomeName"
即可。
SomeName 即为下图中的值。
调试技巧分享
技巧1:修改变量的值
在调试过程中是可以修改变量的值的,这一点在你想要进到一些特定的 if 条件时很有用。
技巧2:设置带条件的断点
很多时候,在循环里我们只想调试具体的某一次,设置 Condition 即可。
技巧3:快速执行到指定代码
Run to Cursor 可以快速执行到光标所在的行。
技巧4:执行表达式
可以执行任意代码,也可以把 if 的判断扔进去执行一下,非常方便。