Try   HackMD

在intel macOS安裝xdebug 來為Laravel專案 Debug

php 版本:8.1
xdebug版本:3.2.2
laravel版本:10.x

安裝xdebug

這邊是macOS安裝,其他作業系統的安裝方式可以參考官網

pecl install xdebug

若出現錯誤,說是已經有這個檔案

Warning: mkdir(): File exists in System.php on line 294
PHP Warning:  mkdir(): File exists in /usr/local/Cellar/php@8.1/8.1.22/share/php@8.1/pear/System.php on line 294

Warning: mkdir(): File exists in /usr/local/Cellar/php@8.1/8.1.22/share/php@8.1/pear/System.php on line 294
ERROR: failed to mkdir /usr/local/Cellar/php@8.1/8.1.22/pecl/20210902

移除已經存在的檔案後重裝,這邊執行移除

rm /usr/local/Cellar/php@8.1/8.1.22/pecl

再次安裝

pecl install xdebug

安裝成功!這邊的xdebug.so路徑要記一下,後面設定php.ini會用到

Build process completed successfully
Installing '/usr/local/Cellar/php@8.1/8.1.22/pecl/20210902/xdebug.so'
install ok: channel://pecl.php.net/xdebug-3.2.2
Extension xdebug enabled in php.ini

調整xdebug位置

確認目前php使用的設定檔php.ini路徑

php --ini

印出的訊息前面會有一些說未找到xdebug的錯誤訊息(因為我們還沒設定),直接拉到最下面找到php.ini路徑

# ...
Configuration File (php.ini) Path: /usr/local/etc/php/8.1
Loaded Configuration File:         /usr/local/etc/php/8.1/php.ini
Scan for additional .ini files in: /usr/local/etc/php/8.1/conf.d
Additional .ini files parsed:      /usr/local/etc/php/8.1/conf.d/ext-opcache.ini

用編輯器進入php.ini準備調整xdebug路徑

vim /usr/local/etc/php/8.1/php.ini

若安裝成功,預設的php.ini長這樣

zend_extension="xdebug.so" # 這是預設的
# ...

改成這樣

;XDebug
zend_extension="/usr/local/Cellar/php@8.1/8.1.22/pecl/20210902/xdebug.so"
xdebug.start_with_request =yes
xdebug.client_port=9003
xdebug.mode=profile,debug
xdebug.output_dir="/tmp"
# ...

稍微說明一下在檔案開頭改成剛剛安裝後的xdebug路徑,在後面加上一些必要的配置,等等即可直接進行debug,詳細的參數說明可參考官方參數說明

由於XDebug2到XDebug3的升級參數有大變更,若需要參考舊的配置參數也要更改,可以參考官網

vscode安裝php debug擴充功能

到這邊安裝Debug擴充
https://marketplace.visualstudio.com/items?itemName=xdebug.php-debug

設定vscode debug啟動檔

直接點擊vscode中的debug工具產生launch.json 或 複製以下程式碼到專案根目錄/.vscode/launch.json

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Listen for Xdebug",
            "type": "php",
            "request": "launch",
            "port": 9003
        }
    ]
}

啟動debug功能

進入debug畫面,點擊啟動

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

啟動Laravel

php artisan serve

完成

接著就能在vscode內設置中斷點了,程式運行到該程式碼就會停下了!

參考