VS Code + Homestead + Xdebug 斷點除錯配置

doderic發表於2018-09-25

一、準備工作

Homestead 開發環境,VS Code 編輯器,Chrome/FF 等開發者友好型瀏覽器。

二、Homestead 中的配置

Homestead 中已經安裝好了 Xdebug,無需再次安裝,透過 phpinfo() 可以看到詳細資訊:
file

  1. 先登入到 Homestead 中
    [your_host Homestead]$ vagrant up && vagrant ssh
  2. 啟用 Xdebug
    vagrant@homestead:~$ xon
  3. 找到 Homestead 虛擬機器的閘道器,方法有多種,這裡使用 route 命令
    vagrant@homestead:~$ route -n

    輸出結果:
    file
    可看到我這裡的閘道器為 10.0.2.2 ,記錄下來

  4. 找到 Xdebug 配置檔案 xdebug.ini 的路徑,注意:請先啟用 Xdebug
    vagrant@homestead:~$ php --ini | grep 'xdebug'

    輸出結果根據實際環境定,我的輸出結果為:

    /etc/php/7.2/cli/conf.d/20-xdebug.ini
  5. 修改該配置檔案
    vagrant@homestead:~$ sudo vim /etc/php/7.2/cli/conf.d/20-xdebug.ini

    將原配置替換為如下:

    zend_extension=xdebug.so
    xdebug.remote_enable=1
    xdebug.remote_autostart=1
    xdebug.remote_host=10.0.2.2 #此處填入剛才獲得的閘道器
  6. 重啟 PHP-FPM 服務
    vagrant@homestead:~$ sudo service php7.2-fpm restart

三、VS Code 中的配置

  1. 安裝並啟用 PHP Debug 擴充套件
    file
  2. 開啟 Debug 皮膚,新增配置項,就是那個齒輪,點選後選擇 PHP
    file
    {
    "version": "0.2.0",
    "configurations": [
       ...
        {
            "name": "Listen for XDebug on Homestead",
            "type": "php",
            "request": "launch",
            "pathMappings": {
                "/home/vagrant/Code": "/home/doderick/Code"    // 此處按實際對映路徑填寫
            },
            "port": 9000
        }
    ]
    }

    此時會在 VS Code 開啟的目錄下生成一個 .vscode/launch.json 檔案用於儲存配置,該配置檔案可供任一置於 /home/vagrant/Code 目錄下的專案使用。

  3. 開啟專案檔案,開始除錯
    file
    回到瀏覽器中訪問一下斷點處的路由
    file
    可以看到左邊欄已經出現了除錯的結果,開始歡樂地除錯吧~

四、 其它

我們並不需要時時刻刻進行除錯,開啟 Xdebug 畢竟也要消耗一些寶貴的系統資源,可以用一條簡單的命令禁用 Xdebug:

vagrant@homestead:~$ xoff
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章