使用 Atom 與 Xdebug 替容器化 PHP 應用除錯

Sep 22, 2016 PHP English

隨著越來越多 PHP 開發者使用 Docker 在不同的環境下進行開發與部署,Debug 的環境、方式也變得較為複雜。因此,本篇將介紹如何使用 Atom、php-debug 與 Xdebug 替容器化 PHP 應用除錯。



在 Docker 容器中安裝與設定 Xdebug

在安裝與設定 Xdebug 前,記得先把 Xdebug 需要使用的 Port 打開,範例如下:

# 假設 Xdebug 需要 port 9000,則加入 -p 9000:9000
docker run -d \
           -p 80:80 \
           -p 9000:9000 \
           ...

接著在容器中安裝 Xdebug,指令如下:

# 進入 Docker 容器
docker exec -it <your-container-name> bash

# 透過 Pecl 安裝 Xdebug
pecl install xdebug

接著在 php.ini (如:/usr/local/etc/php/php.ini) 檔案最後加入 Xdebug 設定,範例如下:

# 省略部分內容 ...

zend_extension=/usr/local/lib/php/extensions/no-debug-non-zts-20131226/xdebug.so
xdebug.remote_enable=1
# 將你的容器 IP 加至 remote_host,例如:
xdebug.remote_host=192.168.99.100
xdebug.remote_connect_back=1
xdebug.remote_port=9000
xdebug.remote_handler=dbgp
xdebug.remote_mode=req
xdebug.remote_autostart=true

為了確保 Xdebug 能正常運作,別忘了重啟該容器。重啟容器指令:

docker restart <your-container-name>


設定 Atom

為了要在 Atom 中 Debug,我們需要安裝 php-debug 套件。透過 apm 安裝套件:

# 安裝 php-debug
apm install php-debug

# 啟用 php-debug
apm enable php-debug

或者,你也可以透過 Settings 進行安裝。安裝後,接著打開 Atom 的設定檔 (config.cson),把 php-debug 設定加至其中。範例如下:

"*":
  "php-debug":
    PathMaps: [
      "/path/to/app/in/docker;/path/to/app/in/local"
    ]
    ServerPort: 9000
  welcome:
    showOnStartup: false


在 Atom 中使用 php-debug

如何除錯?首先開啟檔案,在你想要加入中斷點的地方,使用快捷鍵 fn + alt + F9 插入中斷點,設定好後按下 ctrl + alt + D 開啟 php-debug 視窗,你可以看到顯示 “Listen on port 9000 …“。代表它已經準備好,這時你只需要將頁面重新載入或重新執行程式,就可以看到 php-debug 視窗顯示參數與其他相關資訊。


你也可能會喜歡:




若對於文章內容有任何建議與指正,非常歡迎你告訴我或者與我一起討論 ! :)

zeckli.devforgalaxy@gmail.com   © 2015-2019 zeckli, thanks to Jekyll and GitHub.