Как включить встроенный модуль Xdebug в ServBay
ServBay, мощный интегрированный веб-инструмент, имеет встроенный модуль Xdebug, который очень легко активировать. Xdebug — это инструмент для отладки и анализа PHP, который помогает разработчикам выполнять отладку кода, анализ производительности и проверку покрытия кода, делая его незаменимым для разработки и поддержки PHP приложений.
Введение в модуль Xdebug
Xdebug — это мощное расширение для PHP, предназначенное для отладки и анализа кода PHP. Он предоставляет множество отладочных функций, включая точечную отладку, трассировку стека и наблюдение за переменными. Кроме того, Xdebug поддерживает анализ производительности и проверку покрытия кода, что помогает разработчикам оптимизировать производительность и обеспечить качество кода.
Основные характеристики
- Точечная отладка: Xdebug поддерживает установку точек прерывания в коде, пошаговую отладку кода, что облегчает поиск и исправление ошибок.
- Трассировка стека: При возникновении ошибки Xdebug может генерировать подробную информацию о трассировке стека, помогая разработчикам быстро найти проблему.
- Анализ производительности: Xdebug предоставляет функции анализа производительности, которые позволяют генерировать подробные отчеты о производительности и помогают оптимизировать код.
- Проверка покрытия кода: Xdebug поддерживает проверку покрытия кода, позволяя разработчикам убедиться в том, что тестирование охватывает все пути кода.
- Поддержка интегрированных сред разработки: Xdebug можно интегрировать с различными интегрированными средами разработки (IDE), такими как PHPStorm, Visual Studio Code и др., что обеспечивает удобство отладки.
Версии модуля Xdebug, встроенные в ServBay
ServBay поддерживает несколько версий PHP и предустанавливает соответствующие модули Xdebug для каждой версии. Конкретные версии:
- PHP 5.6, 7.0, 7.1: Xdebug 2.5.5
- PHP 7.2, 7.3, 7.4: Xdebug 3.1.6
- PHP 8.0, 8.1, 8.2, 8.3: Xdebug 3.3.1
- PHP 8.4: Xdebug 3.4.0-dev
Внимание
Порты Xdebug для каждой версии PHP независимы друг от друга и связаны с номером версии, например, порт Xdebug для PHP 7.2
— это 39072
, для PHP 8.3
— 39083
Как включить модуль Xdebug
По умолчанию модуль Xdebug отключен. Процесс его включения очень прост, нужно просто изменить конфигурационный файл соответствующей версии PHP. Вот подробные шаги:
Шаг 1: Найти конфигурационный файл
Сначала найдите директорию conf.d
для соответствующей версии PHP. Например, чтобы активировать Xdebug для PHP 8.3, нужно отредактировать следующий файл:
/Applications/ServBay/etc/php/8.3/conf.d/xdebug.ini
Шаг 2: Редактирование конфигурационного файла
Откройте файл xdebug.ini
и раскомментируйте следующую строку:
[Xdebug]
; Uncomment the following line to enable XDebug
zend_extension = xdebug.so
2
3
Шаг 3: Настройка параметров Xdebug
Для полной функциональности Xdebug можно настроить несколько параметров в xdebug.ini
. Например:
xdebug.mode=debug,develop
xdebug.start_with_request=yes
xdebug.client_host=localhost
xdebug.client_port=39083
xdebug.log=/Applications/ServBay/logs/xdebug/8.3/xdebug.log
2
3
4
5
Шаг 4: Перезапуск сервиса PHP
В панели управления сервисами ServBay перезапустите соответствующий сервис PHP, например, PHP 8.3. После перезапуска модуль Xdebug будет загружен успешно.
Проверка загрузки модуля Xdebug
Можно проверить, загрузился ли модуль Xdebug, создав простой файл PHP. В корневом каталоге веб-сервера создайте файл phpinfo.php
со следующим содержимым:
<?php
phpinfo();
?>
2
3
Перейдите по адресу https://servbay.host/phpinfo.php
и найдите информацию о модуле Xdebug на странице вывода информации о PHP. Если вы видите информацию о Xdebug, значит, модуль загружен успешно.
Настройка Xdebug в PHPStorm
Для использования Xdebug в PHPStorm необходимо выполнить следующие шаги:
Шаг 1: Открытие PHPStorm и вход в настройки
- Откройте PHPStorm.
- Нажмите на меню
File
, затем выберитеSettings
(Windows/Linux) илиPreferences
(macOS).
Шаг 2: Настройка интерпретатора PHP
- В окне настроек перейдите в
Languages & Frameworks
->PHP
. - В разделе
CLI Interpreter
нажмите на правую кнопку...
. - В появившемся окне нажмите на
+
, чтобы добавать новый интерпретатор PHP, выбравLocal
. - Установите путь к интерпретатору PHP, соответствующий версии PHP в ServBay, например
/Applications/ServBay/package/php/8.3/8.3.7/bin/php
. - Нажмите
OK
, чтобы сохранить настройки.
Шаг 3: Настройка Xdebug
Внимание
Порты Xdebug для каждой версии PHP независимы друг от друга и связаны с номером версии, например, порт Xdebug для PHP 7.2
— это 39072
, для PHP 8.3
— 39083
- В окне настроек перейдите в
Languages & Frameworks
->PHP
->Debug
. - В разделе
Xdebug
установите значениеDebug Port
в39083
, соответствующее конфигурацииxdebug.client_port
. - Убедитесь, что опция
Can accept external connections
установлена. - Нажмите
Apply
, затемOK
, чтобы сохранить настройки.
Шаг 4: Настройка PHP веб-сервера
- В окне настроек перейдите в
Languages & Frameworks
->PHP
->Servers
. - Нажмите правую кнопку, чтобы добавать новый сервер.
- Установите имя сервера, например
ServBay Localhost
. - Установите
Host
на соответствующее значение в ServBay, напримерservbay.new
и порт 443 (HTTPS). - Выберите
Debugger
какXdebug
. - Нажмите
OK
, чтобы сохранить настройки.
Шаг 5: Запуск сеанса отладки
- В PHPStorm откройте проект PHP, который хотите отлаживать.
- Установите точку останова в коде (щелкните на пустую область слева от номера строки).
- Нажмите кнопку
Start Listening for PHP Debug Connections
(значок жука) на верхней панели инструментов PHPStorm. - В браузере перейдите к вашему PHP-приложению. Xdebug автоматически подключится к PHPStorm и приостановит выполнение на точке останова.
Заключение
ServBay предоставляет удобный способ управления и включения модуля Xdebug. С помощью простых настроек и перезапуска можно быстро активировать Xdebug для различных версий PHP, чтобы максимально использовать его мощные функции отладки и анализа. Функции точечной отладки, анализа производительности и покрытия кода делают Xdebug незаменимым инструментом для PHP разработчиков.