PhpStorm 使用 Xdebug 來偵錯(deubg)Laravel

其實站長滿喜歡用偵錯 (Debug Mode) 的,因為有時候比較懶的用 print 或是 console 的方法把變數印出來,用 Debug 其實比較方便,應該算個人喜好吧 XD

所以這邊就來教學記錄一下如何在 Mac 把 Xdebug 安裝起來並且讓 PhpStorm 可以監聽到變數。

安裝 brew & php & Xdebug

首先先安裝 brew

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
view raw brew.sh hosted with ❤ by GitHub

安裝 PHP

brew install php
view raw brew-php.sh hosted with ❤ by GitHub

安裝 Xdebug

pecl install xdebug-beta
view raw pecl-xdeubg.sh hosted with ❤ by GitHub

設定 Xdebug

開啟 ext-opcache.ini 在這邊版主裝的版本是 php 7.3 所以設定檔位置如下:

vim /usr/local/etc/php/7.3/conf.d/ext-opcache.ini

基本上裡面的內容要跟如下檔案差不多唯一可能不同的地方是 zend_extension 的地方,這個部分應該裝好會自動幫忙設定好

[opcache]
zend_extension=/usr/local/opt/php/lib/php/20180731/opcache.so
xdebug.idekey = "PHPSTORM"
xdebug.default_enable = 1
xdebug.remote_connect_back = 1
xdebug.remote_port = 9000
xdebug.remote_enable = 1
xdebug.remote_autostart = 1
xdebug.remote_handler="dbgp"

設定 PhpStorm

首先設定 CLI Interpreter,按下 ⌘ Cmd+, 找到左邊的 Languages & Frameworks -> PHP -> CLI Interpreter 找到右邊的

打開之後按下 + 選取 “/usr/local/Cellar/php/7.3.8/bin/php”

如果前面的 Xdebug 設定正確的話,設定完之後應該會如下圖:

設定 PHP Remote Debug

找到上方工具列的 Run -> Edit Configurations,打開之後按左邊的 +,選取 PHP Remote Debug

需要注意的是 IDE key 要跟前面 Xdebug 設定的一樣

設定完如下:

開啟 Web Server

版主因為不想裝 Nginx 或 Apache 所以用 “php artisan serve –port=8080” 開 Server

執行 Debug

按下開始右邊的 Debug,然後用瀏覽器開啟 ”http://localhost:8080″,就可以看到開始 debug 了!

可以在 Sample 的 welcome 頁面下斷點,檔案位置在 routes/web.php 會看到如下圖:

遇到的問題

這邊站長有遇到一個問題是 xdebug 安裝會失敗,錯誤訊息如:

Warning: mkdir(): File exists in System.php on line 294
PHP Warning: mkdir(): File exists in /usr/local/Cellar/php/7.3.8/share/php/pear/System.php on line 294
Warning: mkdir(): File exists in /usr/local/Cellar/php/7.3.8/share/php/pear/System.php on line 294
ERROR: failed to mkdir /usr/local/Cellar/php/7.3.8/pecl/20180731
view raw xdebug-error.sh hosted with ❤ by GitHub

解決方法其實是移除 pecl 就可以了,不過比較簡單的方法我覺得是把 php 跟 xdebug 都移除重新安裝

以上兩種方法提供給大家,如果遇到這個問題可以試試看 ~

總結

這種讓 IDE 幫忙 Debug 的方法版主覺得在某些時候可以加速開發,因為像是會一直有變化的 cookie 或是 session 可以不用一直用印 Log 的方法做 debug,所以如果有需要的朋友可以多多使用 ~

jetbrains 的軟體其實都是需要付費的,如果是學生的話可以多多使用 jetbrains 的 eduction 方案