Xdebug sublime text 3 настройка
Debugging – we all do it a lot. Writing code perfectly the first time around is hard and only a few (if any) succeed at it. More than a year ago, Shameer wrote an article on SitePoint about how you can debug your application using Xdebug and Netbeans. In this article, we are going to have a look at how we can debug using Xdebug in combination with Sublime Text.
Xdebug
In order to be able to debug your PHP scripts, you will need have Xdebug extension installed on your server. See here for installation instructions
Below is a configuration template for php.ini/xdebug.ini, be warned if you are on a Live environment, remote_connect_back allows every debug request from any source to be accepted.
For details about all available settings for configuring Xdebug, see here.
Запустите сеанс Xdebug
Теперь мы можем запустить сеанс Xdebug, чтобы увидеть, все ли настроено правильно. В меню выберите «Инструменты -> Xdebug» и нажмите «Начать отладку» (запустить браузер). Вы заметите, что ваш веб-сайт открыт и что ?XDEBUG_SESSION_START=sublime.xdebug добавляется в конец URL-адреса. Это запустит сеанс xdebug. В Sublime появляются некоторые дополнительные панели, на которых будет отображаться отладочная информация, после того, как вы установили одну или несколько точек останова.
Installation
Package Control
Execute “Package Control: Install Package” in the Command Palette to retrieve a list of available packages. Search in the list and install package Xdebug Client .
Clone the repository by executing the following command in your Packages directory:
Download
Get the latest source from GitHub and extract the source into your Packages directory.
Note: You can locate your Packages directory in the menu under Preferences / Browse Packages.
Commands
Here is a complete list of commands you can find Command Palette under the Xdebug namespace or in the menu under Tools / Xdebug :
Start/Stop debugging session
- Start Debugging - Ctrl+Shift+F9 or ⌘+Shift+F9
- Start Debugging (Launch Browser)
- Restart Session
- Stop Debugging - Ctrl+Shift+F10 or ⌘+Shift+F10
- Stop Debugging (Launch Browser)
- Stop Debugging (Close Windows)
Launch Browser menu option will only show if you have an url configured within settings.
Breakpoints
- Add/Remove Breakpoint - Ctrl+F8 or ⌘+F8
- Set Conditional Breakpoint - Shift+F8
- Clear Breakpoints
- Clear All Breakpoints
Watch expressions
- Set Watch Expression
- Edit Watch Expression
- Remove Watch Expression
- Clear Watch Expressions
Session commands
Continuation commands
- Run - Ctrl+Shift+F5 or ⌘+Shift+F5
- Run To Line
- Step Over - Ctrl+Shift+F6 or ⌘+Shift+F6
- Step Into - Ctrl+Shift+F7 or ⌘+Shift+F7
- Step Out - Ctrl+Shift+F8 or ⌘+Shift+F8
- Stop
- Detach
Other
- Restore Layout / Close Windows - Ctrl+Shift+F11 or ⌘+Shift+F11
- Settings - Default
- Settings - User
Контрольные точки
Давайте установим первую точку останова. Точка останова – это, по сути, флаг, при котором ваше приложение остановится, когда оно достигнет его. В тот момент, когда он останавливается, вы можете проверить все значения переменных, чтобы вы точно знали, что происходит.
Мы можем добавить точку останова, щелкнув правой кнопкой мыши по строке, перейдя к Xdebug, а затем нажав добавить / удалить точку останова. Маркер будет добавлен к желобу линии, чтобы указать, что точка останова была установлена.
Мы снова открываем наш браузер и продолжаем сессию, которую только что начали. Вы заметите, что как только вы перейдете на страницу, где находится точка останова, страница перестанет загружаться. Если вы сейчас откроете Sublime, вы увидите много информации, отображаемой на панелях Xdebug.
Стек Xdebug и контекст Xdebug очень интересны. В стеке вы можете видеть всю трассировку стека, через которую прошел ваш вызов.
В этом контексте вы увидите все глобальные переменные, а также переменные, которые вы определили сами. Вы можете нажать на эти переменные, чтобы увидеть, что именно эти переменные содержат. Например, на скриншоте ниже я щелкнул по переменной $ _SERVER.
Обратите внимание, что желтая стрелка указывает на линию, на которой приложение в данный момент остановлено.
Итак, наше приложение остановилось, и теперь мы можем просматривать определенные переменные. Тем не менее, мы сделали, и мы хотим двигаться дальше. Что теперь? Когда вы снова щелкните правой кнопкой мыши и наведите курсор мыши на меню Xdebug, у вас будет несколько вариантов:
- Запустить который будет запускать приложение до следующей точки останова или до окончания.
- Run to line, которая будет работать до той строки, на которую вы нажали
- Шаг в , шаг в текущую функцию и останавливается сразу после.
- Step over Перешагнет текущую функцию и сразу остановится.
- Step out Выход из текущей функции и остановка сразу после.
- Стоп Остановит отладку.
- Отделить также прекратит отладку.
Бежать и останавливаться довольно легко понять. Методы шага могут быть немного запутанными. Давайте углубимся в это на простом примере.
Представьте, что вы добавили точку останова к первой строке панели методов. Таким образом, в строке с комментарием точки останова ( // breakpoint ).
С шагом в, отладчик перейдет в метод fooBar и остановится на первой строке. Так что в этом случае отладчик остановится на return array_values($arr); линия.
Шаг за шагом вызовет метод, но не остановит. Он остановится на следующей доступной строке после вызова метода. Так что в этом случае он остановится на return $arr;
Наконец, с выходом он будет проходить через весь метод bar и вернется к вызывающей стороне. В этом случае он выйдет из объекта обратно к исходному вызывающему.
Если вы просто решите запустить приложение, оно будет работать дальше до того момента, пока оно не будет выполнено или не возникнет другая точка останова.
Getting started
First of all, we need to have the PHP Xdebug extension installed. If you are uncertain on how to get this done, please have a look at the link provided in the introduction. Make sure that Xdebug is working by checking if it’s listed in your phpinfo() .
Of course we also need Sublime Text. I will be using the latest version: Sublime Text 3. It should also work with Sublime Text 2.
Breakpoints
Let’s set out first breakpoint. A breakpoint is basically a flag where your application will halt when it reaches it. At the moment it halts, you can inspect all the variables’ values so you know actually what is going on.
We can add a breakpoint by clicking with our right mouse on a line, going to Xdebug and then clicking on add/remove breakpoint. A marker will be added to the line gutter to indicate that a breakpoint has been set.
We open up our browser again and continue with the session we just started. You will notice that as soon as you go to the page where the breakpoint is, the page will stop loading. If you now open up Sublime, you will see a lot of information shown in the Xdebug panels.
The Xdebug stack and Xdebug context are very interesting. In the stack, you can see the whole stacktrace your call went through.
In the context, you will see all global variables, but also the variables you defined yourself. You can click on these variables to see exactly these variables are holding. For instance, in the screenshot below, I clicked on the $_SERVER variable.
Notice that a yellow arrow is pointing at the line the application is currently halted on.
So our application halted and now we can look through the variables defined. However, we are done and we want to move on. What now? When you right mouse click once again and hover over the Xdebug menu, you will have several options:
- Run Which will run the application until the next breakpoint or until the ending.
- Run to line which will run until the line you clicked.
- Step into will step into the current function and stops right after.
- Step over Will step over the current function and stops right after.
- Step out Will step out of the current function and stop right after.
- Stop Will stop debugging.
- Detach Will also stop debugging.
Run and stop are quite easy to understand. The step methods could be a little confusing. Let’s dive into these with a simple example.
Imagine you added a breakpoint to the first line of the method bar. So on the line with the breakpoint comment ( // breakpoint ).
With step into, the debugger will step into the fooBar method and will stop there at the first line. So in this case, the debugger will halt on the return array_values($arr); line.
Step over will call the method, but will not stop. It will stop at the next line available after calling the method. So in this case, it will stop at return $arr;
Lastly, with step out it will run through the whole bar method and return to the caller. In this case, it will go out of the object, back to the original caller.
If you just decide to run, the application will run further until the moment it is done executing or another breakpoint occurs.
Настройка Sublime Text 3
Одной из сильных сторон Sublime является то, что вы можете легко расширять ее с помощью пакетов. В этом случае мы собираемся установить пакет Xdebug. Если вы этого еще не сделали, убедитесь, что вы можете установить пакеты, установив управление пакетами .
После того, как вы установили управление пакетами, вы должны запустить Sublime Text 3. Откройте командную палитру из меню инструментов и найдите «install package».
Теперь вы можете искать любой пакет, который вам нравится. В нашем случае мы будем искать пакет «Клиент Xdebug».
Последнее, что нам нужно сделать, это настроить проект в Sublime. Самый простой способ сделать это – открыть корневой каталог вашего приложения, перейти к проектам и нажать «сохранить проекты как». Я предлагаю вам сохранить файл в корне вашего приложения, чтобы вы могли сохранить его в своей системе контроля версий, если вы используете какой-либо файл, и вы можете легко настроить его в любое время.
Откройте только что созданный файл проекта. Содержание будет выглядеть так:
Мы собираемся добавить еще несколько строк:
Как вы можете видеть, я только добавил URL к моему настоящему веб-приложению. Я мог бы установить больше настроек для Xdebug, однако этого достаточно для начала. Я мог бы также установить этот URL в настройках самого Xdebug, но в этом случае я не мог работать над несколькими проектами без необходимости каждый раз изменять конфигурацию Xdebug.
Начиная
Прежде всего, нам нужно установить расширение PHP Xdebug. Если вы не уверены, как это сделать, посмотрите на ссылку, приведенную во введении. Убедитесь, что Xdebug работает, проверив, указан ли он в вашем phpinfo() .
Конечно, нам также нужен Sublime Text. Я буду использовать последнюю версию: Sublime Text 3. Он также должен работать с Sublime Text 2.
Setting up Sublime Text 3
One of the strengths of Sublime is the fact that you can extend it easily with packages. In this case, we are going to install the Xdebug package. If you haven’t done so already, make sure you can install packages by installing package control.
Once you have the package control installed, you should start Sublime Text 3. Open up the command palette from the tools menu and search for “install package”.
Now you can search for any package you like. In our case, we are going to search for the package “Xdebug client”.
The last bit we have to do is set up the project within Sublime. The easiest way to do this is to open up the root directory of your application, go to projects and click on “save projects as”. I suggest you save the file within the root of your application, so you can save it in your version control system if you are using any and you can configure it easily at all times.
Open up the just created project file. The content will look like this:
We are going to add a few more lines:
As you can see, I only added a URL to my actual web application. I could set more settings for Xdebug, however, this is enough to start with. I could have also set this URL in the Xdebug settings itself, but in that case, I couldn’t work on multiple projects without having to change the Xdebug config each time.
Configuration
The following settings can be configured in Xdebug.sublime-settings or in *.sublime-project files:
path_mapping
For remote debugging to resolve the file locations it is required to configure the path mapping with the server path as key and local path as value.
url
Determine which URL to launch in the default web browser when starting/stopping a session.
ide_key
An IDE key is used to identify with debugger engine when Sublime Text will start or stop a debugging session.
This package does not filter sessions by IDE key, it will accept any IDE key, also ones that do not match this configured IDE key. It is merely used when launching the default web browser with the configured URL.
host
Host address of network interface which Sublime Text should listen to connect with debugger engine.
When specifying host address of network interface, be sure to specify an IPv4 address as Sublime Text will listen for connections through an IPv4 socket.
port
Which port number Sublime Text should listen to connect with debugger engine.
max_children
Maximum amount of array children and object's properties to return.
max_data
Maximum amount of variable data to initially retrieve.
max_depth
Maximum amount of nested levels to retrieve of array elements and object properties.
break_on_start
Break at first line on session start, when debugger engine has connected.
break_on_exception
Break on exceptions, suspend execution when the exception name matches an entry in this list value.
close_on_stop
Always close debug windows and restore layout on session stop.
super_globals
Show information about super globals in context view.
fullname_property
Display property by fullname in context view.
hide_password
Do not show possible password values in context view.
pretty_output
Render evaluated result as parsed output instead of raw XML.
launch_browser
Always launch browser on session start/stop.
This will only work if you have the 'url' setting configured.
browser_no_execute
When launching browser on session stop do not execute script.
By using parameter XDEBUG_SESSION_STOP_NO_EXEC instead of XDEBUG_SESSION_STOP.
disable_layout
Do not use the debugging window layout.
debug_layout
Window layout that is being used when debugging.
breakpoint_group
breakpoint_index
context_group
context_index
stack_group
stack_index
watch_group
watch_index
Group and index positions for debug views.
breakpoint_enabled
breakpoint_disabled
breakpoint_current
current_line
Custom gutter icons for indicating current line or enabled/disabled breakpoints.
Do not use same icon for above values, because Sublime Text is unable to use the same icon for different scopes, in case there are duplicate icons detected it will fall back to the corresponding icon in the package.
python_path
Path to Python installation on your system.
Which is being used to load missing modules.
debug
Show detailed log information about communication between debugger engine and Sublime Text.
Below are examples how to configure your Xdebug.sublime-settings and *.sublime-project files.
Xdebug.sublime-settings
*.sublime-project
Overview
Getting started
First of all, we need to have the PHP Xdebug extension installed. If you are uncertain on how to get this done, please have a look at the link provided in the introduction. Make sure that Xdebug is working by checking if it’s listed in your phpinfo() .
Of course we also need Sublime Text. I will be using the latest version: Sublime Text 3. It should also work with Sublime Text 2.
Conclusion
In this article we saw how we could integrate Xdebug with Sublime and made sure we understood how to debug. Almost every IDE suitable for PHP can integrate with Xdebug. If you are interested in debugging like this in Netbeans, have a look at the article mentioned in the introduction. Are you using breakpoints? Or are you using PHP functions like var_dump to get your debug data? Let us know in the comments below!
Установка Sublime Plugin
Чтобы установить плагин Sublime Text Xdebug, вам нужно будет выполнить следующие шаги:
Шаг 1 – Установить установку палитры управления пакетами с помощью сочетания клавиш Ctrl + Shift + P или Cmd + shift + P.
Шаг 2. После успешной установки клиента Xdebug файл конфигурации будет сохранен в папке « Установленные пакеты ». Файл конфигурации представляет собой файл JSON, который содержит параметры для отладки веб-приложения PHP.
Шаг 3 – Запустите сеанс отладки PHP-файла с помощью комбинации клавиш Ctrl + F9 . Вы также можете сделать это, используя опцию Start Debug, используя палитру команд.
Шаг 4 – Разделенные окна XdebugClient покажут вывод файла PHP. Он поддерживает процесс отладки кода построчно. Обратитесь к следующему скриншоту для лучшего понимания –
Xdebug debugger client integration for Sublime Text.
Based on the Xdebug protocol functionality in SublimeXdebug package by Kindari.
- Remote debugging by configuring path mapping
- Navigate on breakpoint hit to relevant file on specific line, when found on local drive
- Customizable debugging layout for displaying stack history and context variables with syntax
- Overview of breakpoints in all files and disable/enable breakpoints with simple click
- Evaluate code within the current execution context, by setting watch expressions
- Inspect (nested) context variables
- Works on both Sublime Text 2 and 3
Here is a complete list of commands you can find Command Palette under the Xdebug namespace or in the menu under Tools / Xdebug :
Start/Stop debugging session
- Start Debugging - Ctrl+Shift+F9 or ⌘+Shift+F9
- Start Debugging (Launch Browser)
- Restart Session
- Stop Debugging - Ctrl+Shift+F10 or ⌘+Shift+F10
- Stop Debugging (Launch Browser)
- Stop Debugging (Close Windows)
Launch Browser menu option will only show if you have an url configured within settings.
- Add/Remove Breakpoint - Ctrl+F8 or ⌘+F8
- Set Conditional Breakpoint - Shift+F8
- Clear Breakpoints
- Clear All Breakpoints
- Set Watch Expression
- Edit Watch Expression
- Remove Watch Expression
- Clear Watch Expressions
- Run - Ctrl+Shift+F5 or ⌘+Shift+F5
- Run To Line
- Step Over - Ctrl+Shift+F6 or ⌘+Shift+F6
- Step Into - Ctrl+Shift+F7 or ⌘+Shift+F7
- Step Out - Ctrl+Shift+F8 or ⌘+Shift+F8
- Stop
- Detach
- Restore Layout / Close Windows - Ctrl+Shift+F11 or ⌘+Shift+F11
- Settings - Default
- Settings - User
Execute "Package Control: Install Package" in the Command Palette to retrieve a list of available packages. Search in the list and install package Xdebug Client .
Clone the repository by executing the following command in your Packages directory:
Get the latest source from GitHub and extract the source into your Packages directory.
Note: You can locate your Packages directory in the menu under Preferences / Browse Packages.
In order to be able to debug your PHP scripts, you will need have Xdebug extension installed on your server. See here for installation instructions
Below is a configuration template for php.ini/xdebug.ini, be warned if you are on a Live environment, remote_connect_back allows every debug request from any source to be accepted.
For details about all available settings for configuring Xdebug, see here.
The following settings can be configured in Xdebug.sublime-settings or in *.sublime-project files:
path_mapping
For remote debugging to resolve the file locations it is required to configure the path mapping with the server path as key and local path as value.
url
Determine which URL to launch in the default web browser when starting/stopping a session.
ide_key
An IDE key is used to identify with debugger engine when Sublime Text will start or stop a debugging session.
This package does not filter sessions by IDE key, it will accept any IDE key, also ones that do not match this configured IDE key. It is merely used when launching the default web browser with the configured URL.
host
Host address of network interface which Sublime Text should listen to connect with debugger engine.
When specifying host address of network interface, be sure to specify an IPv4 address as Sublime Text will listen for connections through an IPv4 socket.
port
Which port number Sublime Text should listen to connect with debugger engine.
max_children
Maximum amount of array children and object's properties to return.
max_data
Maximum amount of variable data to initially retrieve.
max_depth
Maximum amount of nested levels to retrieve of array elements and object properties.
break_on_start
Break at first line on session start, when debugger engine has connected.
break_on_exception
Break on exceptions, suspend execution when the exception name matches an entry in this list value.
close_on_stop
Always close debug windows and restore layout on session stop.
super_globals
Show information about super globals in context view.
fullname_property
Display property by fullname in context view.
hide_password
Do not show possible password values in context view.
pretty_output
Render evaluated result as parsed output instead of raw XML.
launch_browser
Always launch browser on session start/stop.
This will only work if you have the 'url' setting configured.
browser_no_execute
When launching browser on session stop do not execute script.
By using parameter XDEBUG_SESSION_STOP_NO_EXEC instead of XDEBUG_SESSION_STOP.
disable_layout
Do not use the debugging window layout.
debug_layout
Window layout that is being used when debugging.
breakpoint_group
breakpoint_index
context_group
context_index
stack_group
stack_index
watch_group
watch_index
Group and index positions for debug views.
breakpoint_enabled
breakpoint_disabled
breakpoint_current
current_line
Custom gutter icons for indicating current line or enabled/disabled breakpoints.
Do not use same icon for above values, because Sublime Text is unable to use the same icon for different scopes, in case there are duplicate icons detected it will fall back to the corresponding icon in the package.
python_path
Path to Python installation on your system.
Which is being used to load missing modules.
debug
Show detailed log information about communication between debugger engine and Sublime Text.
Below are examples how to configure your Xdebug.sublime-settings and *.sublime-project files.
Xdebug.sublime-settings
*.sublime-project
No. Having installed both packages can cause conflicts, because they might both listen to the same port for a debugger engine response and have similar keymapping.
However (project) settings from SublimeXdebug are compatible with SublimeTextXdebug.
How can I start a debugging session?
SublimeTextXdebug can start or stop a debugging session by launching the default web browser with the configured URL and parameter XDEBUG_SESSION_START or XDEBUG_SESSION_STOP which uses the configured IDE key as value. By default the IDE key is sublime.xdebug .
When you do not configure the URL, the plugin will still listen for debugging connections from Xdebug, but you will need to trigger Xdebug for a remote session.
If you want to run a start a debugging session from command line, before you run your script, you will need to set the environment variable XDEBUG_CONFIG with the IDE key.
Windows
UNIX
Make sure before defining the environment variable you have switched to the proper user environment.
As example you would set the environment variable as guest and execute the script as root (sudo), then root will not have the environment variable XDEBUG_CONFIG that was defined by guest.
How do I set a breakpoint and/or watch expression?
With SublimeTextXdebug you can easily add/remove breakpoints, which are send on session start.
Or set/edit/remove watch expressions, that are evaluated in the current execution context.
Setting a conditional breakpoints or watch expressions is quite easy, it is like an if statement in PHP.
As example you only want to stop on breakpoint when value of $number is equal to 13, then your Breakpoint condition would be $number==13 .
Another example would be when you would like to know the value of $item['image'] on each break, then your Watch expression would be $item['image'] .
Another way is to set the breakpoint in your PHP code with the following function xdebug_break() .
How to configure or disable breaking on exceptions?
By default the execution of a debugging session is suspended on each of the following exception names:
- "Fatal error" - E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR
- "Catchable fatal error" - E_RECOVERABLE_ERROR (since PHP 5.2.0)
- "Warning" - E_WARNING, E_CORE_WARNING, E_COMPILE_WARNING, E_USER_WARNING
- "Parse error" - E_PARSE
- "Notice" - E_NOTICE, E_USER_NOTICE
- "Strict standards" - E_STRICT
- "Deprecated" - E_DEPRECATED, E_USER_DEPRECATED (since PHP 5.3.0)
- "Xdebug"
- "Unknown error"
In order to specify which exception names to suspend the execution of a debugging session, configure the break_on_exception setting with a list of the specific exception names by choice from the list shown above.
It is also possible to specify custom exceptions instead of all exceptions ("Fatal error"). For example if you would configure "MissingArgumentException" instead of "Fatal error", it would not break on "InvalidParameterException".
To disable breaking on exceptions either configure an empty list break_on_exception: [] or set as break_on_exception: false .
How can I customize/disable the debugging layout?
Re-adjust the layout in Sublime Text to your liking and then in console ( Ctrl+` ) you type window.get_layout() and set that value as your debug_layout .
Further customizing can be done by assigning the Xdebug views to a group/index with the breakpoint_group , breakpoint_index , context_group , context_index , stack_group , stack_index , watch_group , watch_index settings.
Or you can disable the debugging layout by setting disable_layout: true , which will open all Xdebug views in current active group/window on session start and does not change your layout.
How to solve ImportError ?
Older versions of Sublime Text do not come with Python bundled and rely on your Python system installation.
Some systems do not include specific modules which are required by this package, such as pyexpat.
Configure the python_path setting to the path of your Python installation on your system which is either newer or has all required modules. For example: "python_path" : "/usr/lib/python2.7" .
What to do when you experience any issues?
First check following possible solutions that could resolve any issues:
- Use absolute paths in your path_mapping setting, Xdebug does not return symbolic links.
- Breakpoint is on an empty line, Xdebug does not stop on empty lines.
- Set port and xdebug.remote_port to different port (9001), default port 9000 might already be used by an other application.
- Add an exception for Sublime Text (plugin_host.exe) to your firewall, response from Xdebug could be blocked by firewall.
- Lower the max_data / max_depth / max_children settings to increase response speed or prevent crashing, Xdebug could return to much data to process.
- Change permissions for Sublime Text and it's packages on your filesystem, Sublime Text or package might not have valid rights.
Do you still experience any issues, then create an issue including the following data:
Based on the Xdebug protocol functionality in SublimeXdebug package by Kindari.
Setting up Xdebug
We need to configure xdebug by adding the following to your php.ini file, or even better, to an xdebug.ini file as described here under How-to On Linux.
In general you will be using 127.0.0.1 as your host. However, If you are using vagrant for example, you will be using something like 10.0.2.2, depending on where Xdebug can find your system.
The remote log is not necessary, but in case of problems, it’s the place where you can find information about errors that occurred.
Don’t forget to restart your webserver!
Share This Article
Peter is a software architect from the Netherlands. He freelanced for more then 6 years as a web developer, and meanwhile, he graduated as software engineer with honors. He decided to join CMNTY Corporation which specializes in creating community software and is now responsible for the ongoing development of multiple web applications as well as mobile applications. Peter believes a real developer is able to combine multiple techniques together to make sure the user receives the ultimate experience and enjoys using the application. In his free time, he loves to play board games with anyone who is interested. He especially has a passion for cooperative board games.
Отладка – мы все делаем это много. Писать код идеально с первого раза сложно, и лишь немногие (если таковые имеются) преуспевают в этом. Более года назад Шамер написал в SitePoint статью о том, как можно отлаживать приложение с помощью Xdebug и Netbeans. В этой статье мы рассмотрим, как мы можем отлаживать, используя Xdebug в сочетании с Sublime Text.
Start the Xdebug session
We can now start the Xdebug session to see if everything is set up properly. In the menu, click on tools -> Xdebug and click on start debugging (launch browser). You will notice that your website is opened up and that ?XDEBUG_SESSION_START=sublime.xdebug is added to the end of the URL. This will start the xdebug session. In Sublime, some extra panels appear where debug information will be shown, after you have set one or more breakpoints.
Настройка Xdebug
Нам нужно настроить xdebug, добавив следующее в файл php.ini или, что еще лучше, в файл xdebug.ini как описано здесь в разделе «Практические xdebug.ini по Linux».
В общем, вы будете использовать 127.0.0.1 в качестве хоста. Однако, если вы используете vagrant, например, вы будете использовать что-то вроде 10.0.2.2, в зависимости от того, где Xdebug может найти вашу систему.
Удаленный журнал не нужен, но в случае проблем это место, где вы можете найти информацию об ошибках, которые произошли.
Не забудьте перезапустить ваш веб-сервер!
Вывод
В этой статье мы увидели, как мы можем интегрировать Xdebug с Sublime, и убедились, что понимаем, как отлаживать. Почти каждая IDE, подходящая для PHP, может интегрироваться с Xdebug. Если вы заинтересованы в такой отладке в Netbeans, посмотрите статью, упомянутую во введении. Вы используете точки останова? Или вы используете функции PHP, такие как var_dump, для получения данных отладки? Дайте нам знать в комментариях ниже!
Отладка – это процесс поиска ошибок и ошибок в данном коде и их исправления. Sublime редактор включает в себя различные плагины, которые имеют функции отладки, которые помогают легко находить ошибки.
В этой главе вы узнаете, как отлаживать веб-приложение на PHP. Для этой цели Sublime использует подключаемый модуль Sublime TestX . Особенности этого плагина –
Это расширение используется для отладки файлов и скриптов PHP.
Предоставляет список возможностей отладки и профилирования.
Поддерживает трассировку стека и параметры реального времени, такие как отображение и функциональность.
Это расширение используется для отладки файлов и скриптов PHP.
Предоставляет список возможностей отладки и профилирования.
Поддерживает трассировку стека и параметры реального времени, такие как отображение и функциональность.
Troubleshoot
Can I have both SublimeTextXdebug and SublimeXdebug installed?
No. Having installed both packages can cause conflicts, because they might both listen to the same port for a debugger engine response and have similar keymapping.
However (project) settings from SublimeXdebug are compatible with SublimeTextXdebug.
How can I start a debugging session?
SublimeTextXdebug can start or stop a debugging session by launching the default web browser with the configured URL and parameter XDEBUG_SESSION_START or XDEBUG_SESSION_STOP which uses the configured IDE key as value. By default the IDE key is sublime.xdebug .
When you do not configure the URL, the plugin will still listen for debugging connections from Xdebug, but you will need to trigger Xdebug for a remote session.
If you want to run a start a debugging session from command line, before you run your script, you will need to set the environment variable XDEBUG_CONFIG with the IDE key.
Windows
UNIX
Make sure before defining the environment variable you have switched to the proper user environment.
As example you would set the environment variable as guest and execute the script as root (sudo), then root will not have the environment variable XDEBUG_CONFIG that was defined by guest.
How do I set a breakpoint and/or watch expression?
With SublimeTextXdebug you can easily add/remove breakpoints, which are send on session start.
Or set/edit/remove watch expressions, that are evaluated in the current execution context.
Setting a conditional breakpoints or watch expressions is quite easy, it is like an if statement in PHP.
As example you only want to stop on breakpoint when value of $number is equal to 13, then your Breakpoint condition would be $number==13 .
Another example would be when you would like to know the value of $item['image'] on each break, then your Watch expression would be $item['image'] .
Another way is to set the breakpoint in your PHP code with the following function xdebug_break() .
How to configure or disable breaking on exceptions?
By default the execution of a debugging session is suspended on each of the following exception names: * “Fatal error” - E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR * “Catchable fatal error” - E_RECOVERABLE_ERROR (since PHP 5.2.0) * “Warning” - E_WARNING, E_CORE_WARNING, E_COMPILE_WARNING, E_USER_WARNING * “Parse error” - E_PARSE * “Notice” - E_NOTICE, E_USER_NOTICE * “Strict standards” - E_STRICT * “Deprecated” - E_DEPRECATED, E_USER_DEPRECATED (since PHP 5.3.0) * “Xdebug” * “Unknown error”
In order to specify which exception names to suspend the execution of a debugging session, configure the break_on_exception setting with a list of the specific exception names by choice from the list shown above.
It is also possible to specify custom exceptions instead of all exceptions (“Fatal error”). For example if you would configure “MissingArgumentException” instead of “Fatal error”, it would not break on “InvalidParameterException”.
To disable breaking on exceptions either configure an empty list break_on_exception: [] or set as break_on_exception: false .
How can I customize/disable the debugging layout?
Re-adjust the layout in Sublime Text to your liking and then in console ( Ctrl+` ) you type window.get_layout() and set that value as your debug_layout .
Further customizing can be done by assigning the Xdebug views to a group/index with the breakpoint_group , breakpoint_index , context_group , context_index , stack_group , stack_index , watch_group , watch_index settings.
Or you can disable the debugging layout by setting disable_layout: true , which will open all Xdebug views in current active group/window on session start and does not change your layout.
How to solve ImportError ?
Older versions of Sublime Text do not come with Python bundled and rely on your Python system installation.
Some systems do not include specific modules which are required by this package, such as pyexpat.
Configure the python_path setting to the path of your Python installation on your system which is either newer or has all required modules. For example: "python_path" : "/usr/lib/python2.7" .
What to do when you experience any issues?
First check following possible solutions that could resolve any issues:
- Use absolute paths in your path_mapping setting, Xdebug does not return symbolic links.
- Breakpoint is on an empty line, Xdebug does not stop on empty lines.
- Set port and xdebug.remote_port to different port (9001), default port 9000 might already be used by an other application.
- Add an exception for Sublime Text (plugin_host.exe) to your firewall, response from Xdebug could be blocked by firewall.
- Lower the max_data / max_depth / max_children settings to increase response speed or prevent crashing, Xdebug could return to much data to process.
- Change permissions for Sublime Text and it's packages on your filesystem, Sublime Text or package might not have valid rights.
Do you still experience any issues, then create an issue including the following data:
Features
- Remote debugging by configuring path mapping
- Navigate on breakpoint hit to relevant file on specific line, when found on local drive
- Customizable debugging layout for displaying stack history and context variables with syntax
- Overview of breakpoints in all files and disable/enable breakpoints with simple click
- Evaluate code within the current execution context, by setting watch expressions
- Inspect (nested) context variables
- Works on both Sublime Text 2 and 3
Читайте также: