Настройка visual studio code для php
Manage pull requests and conduct code reviews in your IDE with full source-tree context. Comment on any line, not just the diffs. Use jump-to-definition, your favorite keybindings, and code intelligence with more of your workflow.
Learn More
Sponsor PHP Debug Adapter for Visual Studio Code
If you find this extension useful, if it helps you solve your problems and if you appreciate the support given here, consider sponsoring our work.
Installation
Install the extension: Press F1 , type ext install php-debug .
This extension is a debug adapter between VS Code and Xdebug by Derick Rethans. Xdebug is a PHP extension (a .so file on Linux and a .dll on Windows) that needs to be installed on your server.
Install Xdebug I highly recommend you make a simple test.php file, put a phpinfo(); statement in there, then copy the output and paste it into the Xdebug installation wizard. It will analyze it and give you tailored installation instructions for your environment. In short:
- On Windows: Download the appropriate precompiled DLL for your PHP version, architecture (64/32 Bit), thread safety (TS/NTS) and Visual Studio compiler version and place it in your PHP extension folder.
- On Linux: Either download the source code as a tarball or clone it with git, then compile it. Or see if your distribution already offers prebuilt packages.
Configure PHP to use Xdebug by adding zend_extension=path/to/xdebug to your php.ini. The path of your php.ini is shown in your phpinfo() output under "Loaded Configuration File".
Enable remote debugging in your php.ini :
For Xdebug v3.x.x:
For Xdebug v2.x.x:
If you are doing web development, don't forget to restart your webserver to reload the settings.
Verify your installation by checking your phpinfo() output for an Xdebug section.
VS Code Configuration
In your project, go to the debugger and hit the little gear icon and choose PHP. A new launch configuration will be created for you with three configurations:
- Listen for Xdebug This setting will simply start listening on the specified port (by default 9003) for Xdebug. If you configured Xdebug like recommended above, every time you make a request with a browser to your webserver or launch a CLI script Xdebug will connect and you can stop on breakpoints, exceptions etc.
- Launch currently open script This setting is an example of CLI debugging. It will launch the currently opened script as a CLI, show all stdout/stderr output in the debug console and end the debug session once the script exits.
- Launch Built-in web server This configuration starts the PHP built-in web server on a random port and opens the browser with the serverReadyAction directive. The port is random (localhost:0) but can be changed to a desired fixed port (ex: localhost:8080). If a router script is needed, add it with program directive. Additional PHP/Xdebug directives trigger debugging on every page load.
There are also configurations for Xdebug v2 (Legacy) installations.
Note: You can even debug a script without launch.json . If no folder is open, and the VS Code status bar is purple, pressing F5 will start the open script with Xdebug3 specific parameters. If the php executable is not in path, you can provide it with the setting php.debug.executablePath . For debugging to work, Xdebug must still be correctly installed.
Supported launch.json settings:
- request : Always "launch"
- hostname : The address to bind to when listening for Xdebug (default: all IPv6 connections if available, else all IPv4 connections) or Unix Domain socket (prefix with unix:// ) or Windows Pipe ( \\?\pipe\name ) - cannot be combined with port
- port : The port on which to listen for Xdebug (default: 9003 ). If port is set to 0 a random port is chosen by the system and a placeholder $ is replaced with the chosen port in env and runtimeArgs .
- stopOnEntry : Whether to break at the beginning of the script (default: false )
- pathMappings : A list of server paths mapping to the local source paths on your machine, see "Remote Host Debugging" below
- log : Whether to log all communication between VS Code and the adapter to the debug console. See Troubleshooting further down.
- ignore : An optional array of glob patterns that errors should be ignored from (for example **/vendor/**/*.php )
- maxConnections : Accept only this number of parallel debugging sessions. Additional connections will be dropped and their execution will continue without debugging.
- proxy : DBGp Proxy settings
- enable : To enable proxy registration set to true (default is `false).
- host : The address of the proxy. Supports host name, IP address, or Unix domain socket (default: 127.0.0.1).
- port : The port where the adapter will register with the the proxy (default: 9001 ).
- key : A unique key that allows the proxy to match requests to your editor (default: vsc ). The default is taken from VSCode settings php.debug.idekey .
- timeout : The number of milliseconds to wait before giving up on the connection to proxy (default: 3000 ).
- allowMultipleSessions : If the proxy should forward multiple sessions/connections at the same time or not (default: true ).
- max_children : max number of array or object children to initially retrieve
- max_data : max amount of variable data to initially retrieve.
- max_depth : maximum depth that the debugger engine may return when sending arrays, hashes or object structures to the IDE (there should be no need to change this as depth is retrieved incrementally, large value can cause IDE to hang).
- show_hidden : This feature can get set by the IDE if it wants to have more detailed internal information on properties (eg. private members of classes, etc.) Zero means that hidden members are not shown to the IDE.
Options specific to CLI debugging:
- program : Path to the script that should be launched
- args : Arguments passed to the script
- cwd : The current working directory to use when launching the script
- runtimeExecutable : Path to the PHP binary used for launching the script. By default the one on the PATH.
- runtimeArgs : Additional arguments to pass to the PHP binary
- externalConsole : Launches the script in an external console window instead of the debug console (default: false )
- env : Environment variables to pass to the script
Features
- Line breakpoints
- Conditional breakpoints
- Hit count breakpoints: supports the conditions like >=n , ==n and %n
- Function breakpoints
- Step over, step in, step out
- Break on entry
- Start with Stop on entry (F10/F11)
- Breaking on uncaught exceptions and errors / warnings / notices
- Multiple, parallel requests
- Stack traces, scope variables, superglobals, user defined constants
- Arrays & objects (including classname, private and static properties)
- Debug console
- Watches
- Set variables
- Run as CLI
- Run without debugging
- DBGp Proxy registration and unregistration support
Remote Host Debugging
To debug a running application on a remote host, you need to tell Xdebug to connect to a different IP than localhost . This can either be done by setting xdebug.client_host to your IP or by setting xdebug.discover_client_host = 1 to make Xdebug always connect back to the machine who did the web request. The latter is the only setting that supports multiple users debugging the same server and "just works" for web projects. Again, please see the Xdebug documentation on the subject for more information.
To make VS Code map the files on the server to the right files on your local machine, you have to set the pathMappings settings in your launch.json. Example:
Please also note that setting any of the CLI debugging options will not work with remote host debugging, because the script is always launched locally. If you want to debug a CLI script on a remote host, you need to launch it manually from the command line.
Proxy support
The debugger can register itself to a DBGp proxy with a IDE Key. The proxy will then forward to the IDE only those DBGp sessions that have this specified IDE key. This is helpful in a multiuser environment where developers cannot use the same DBGp port at the same time. Careful setup is needed that requests to the web server contain the matching IDE key.
The official implementation of the dbgpProxy.
A Xdebug helper browser extension is also recommended. There the request side IDE key can be easily configured.
Troubleshooting
- Ask a question on StackOverflow
- If you think you found a bug, open an issue
- Make sure you have the latest version of this extension and Xdebug installed
- Try out a simple PHP file to recreate the issue, for example from the testproject
- Set "log": true in your launch.json and observe Debug Console panel
- In your php.ini, set xdebug.log = /path/to/logfile (make sure your webserver has write permissions to the file)
- Reach out on Twitter @damjancvetko
Contributing
To hack on this adapter, clone the repository and open it in VS Code. You need NodeJS with NPM installed and in your PATH. Also a recent PHP and Xdebug should be installed and in your PATH.
- Install NPM packages by either running npm install on command line in the project directory or selecting Terminal / Run Task. / npm / npm: install in VS Code menu.
- Run the build/watch process either by running npm run watch on command line in the project directory or selecting Terminal / Run Build Task. in VS Code menu.
- Start the debug adapter by opening the Run and Debug side bar, selecting Debug adapter configuration and clicking on the green Run arrow (or hitting F5 ). The compiled adapter will be running in "server mode" and listening on TCP port 4711.
- Run a separate instance of VS Code, called "Extension Development Host" by running code testproject --extensionDevelopmentPath=. on command line in the project directory or selecting the Launch Extension Run and Debug configuration and pressing the green Run arrow. Another shortcut is to run npm run start . You can also run an Insiders build of VS Code for testing newer features.
- In the "Extension Development Host" instance open .vscode/launch.json and uncomment the debugServer configuration line. Run your PHP debug session by selecting the desired configuration and hitting F5 . Now you can debug the testproject like specified above and set breakpoints inside your first VS Code instance to step through the adapter code.
Tests are written with Mocha and can be run with npm test or from Terminal / Run Task. / npm: test . When you submit a PR the tests will be run in CI on Linux, macOS and Windows against multiple PHP and Xdebug versions.
Before submitting a PR also run npm run lint or Terminal / Run Tasks. / npm: lint .
В некоторых случаях может возникнуть необходимость отладки приложений на php. Visual Studio code предоставляет такую возможность при условии установки дополнительного расширения PHP Debug (marketplace, github).
Установка PHP Debug
Для установки нажмите Ctrl+p и введите команду ext install php-debug . Нажмите на кнопку «включить», в итоге вы должны увидеть примерно следующее:
Установка и настройка Xdebug
PHP Debug использует для отладки Xdebug. Для настройки Xdebug пройдите по ссылке. Предполагается, что на локальной машине уже установлен и настроен сервер apache. Здесь и далее действия указаны для Windows. Можно создать файл, например, test.php содержащий:
Открыть его в браузере и скопировать содержимое страницы в диалоговое окно. Другой способ:
- win+R ;
- cmd + Enter ;
- php -i > phpinfo.text ;
- открыть любым удобным редактором phpinfo.txt и все его содержимое вставить в диалоговое окно.
Далее следуйте инструкциям по установке: скачайте .dll и не изменяя его имени скопируйте его в указанную папку, дополните файл php.ini указанной в руководстве строкой.
Кроме этого, добавьте нижеследующие строки. Итоговое добавление будет примерно таким:
Как вы уже, возможно догадались, в данном примере на локальной машине установлен XAMPP.
Обратите внимание на строку xdebug.remote_host=127.0.0.2 . По умолчанию Xdebug "слушает" порт 127.0.0.1. Укажите здесь, адрес отлаживаемого сайта.
Примечание: С версией Xdebug 2.5 и выше Visual Studio code не работает. Поэтому выбирайте соответствующий вашей версии php файл *.dll.
Настройка Visual Studio code
Вызовите панель отладки (1) и нажмите на иконку с маленькой шестеренкой (2).
В появившемся списке выберите PHP . Автоматически сформируется файл launch.json .
Настройка PHP Debug на этом окончена.
Отладка php в Visual Studio code
Пора перейти от слов к действиям и познакомиться с Visual Studio Code поближе. В этом посте представлена поэтапная настройка VS Code для разработки на PHP.
Скачайте и установите Visual Studio Code
- Бесплатный: да, VS Code полностью бесплатен, никаких приписок мелким шрифтом.
- Кроссплатформенный: доступны версии VS Code для Windows, Linux и OS X.
- Легковесный: VS Code, в отличие от Visual Studio, — не полнофункциональная среда IDE, а редактор кода. Он поддерживает ряд мощных функций, характерных для IDE, например, IntelliSense, отладку и интеграцию с системой управления исходным кодом Git.
После загрузки установите редактор на своем компьютере. Подробные инструкции по установке доступны здесь. Теперь можно открыть окно командной строки, запустить Visual Studio Code и начать редактировать файлы в папке.
Если вы откроете файл с расширением .php, Code поймет, что это файл на языке PHP. Тип файла можно изменить и вручную: щелкните кнопку Language Mode в правом нижнем углу окна редактора или последовательно нажмите клавиши Ctrl+K и M.
Встроенные функции работы с PHP
VS Code поддерживает множество языков, в том числе PHP. На портале Visual Studio Marketplace доступны расширения VS Code, обеспечивающие поддержку дополнительных языков. Для PHP работает подсветка синтаксиса, определение парных скобок и фрагменты кода.
Когда вы начнете набирать код в файле PHP, то заметите автоматическое срабатывание цветового выделения синтаксиса, определения парных скобок и функции IntelliSense.
Настройка статического анализа PHP
Необходимо указать путь к исполняемому файлу PHP на вашем компьютере. Для этого следует изменить файл настроек (в VS Code существуют различные уровни файлов настроек, подробнее см. в документации). В нашем примере мы настроим параметры PHP глобально для пользователя.
Откройте пользовательские настройки с помощью панели команд: нажмите F1, введите «user» и нажмите Enter.
Откроется два документа JSON. В документе слева содержатся настройки по умолчанию, в документе справа — пользовательские настройки. В пользовательских настройках можно переопределить настройки по умолчанию. Чтобы включить статический анализ кода PHP, необходимо изменить значения трех параметров.
Чтобы настроить путь к исполняемому файлу PHP, укажите его в файле пользовательских настроек:
После этого функция проверки будет включена для всех файлов PHP. Некорректный код PHP будет подчеркнут красным (в примере ниже пропущена точка с запятой).
Настройка отладки
Расширение PHP Debug (спасибо Феликсу Беккеру!) добавляет в VS Code поддержку отладчика XDebug. Установите расширение через панель команд VS Code: нажмите F1, введите «install ext», нажмите Enter, введите «PHP Debug» и вновь нажмите Enter. После установки расширения может потребоваться перезапуск VS Code.
Убедитесь, что корневой раздел веб-сервера соответствует вашему проекту. Тогда при каждом запросе файла PHP XDebug будет предпринимать попытку подключения к порту 9000 для отладки.
Чтобы начать отладку, откройте вкладку Debugging в VS Code.Щелкните значок шестеренки, чтобы сформировать файл launch.json, который позволит VS Code начать сеанс отладки XDebug.
Чтобы начать отладку, нажмите F5 или щелкните зеленую стрелку на вкладке Debugging. Чтобы задать точку останова в исходном коде, выберите строку и нажмите F9.Теперь, когда вы откроете определенную веб-страницу, VS Code остановит выполнение исходного кода в заданной точке. В области слева отобразится информация о переменных, стеке вызовов и т. п.
Заключение
Visual Studio Code обладает отличной встроенной поддержкой PHP, а расширение PHP Debug добавляет возможность отладки кода на PHP. Все эти инструменты являются бесплатными и кроссплатформенными.
На портале Visual Studio Marketplace доступны и другие расширения для работы с PHP.
Так может выглядеть интерфейс редактора после установки расширений
Основные возможности
- отладчик кода
- встроенный терминал
- удобные инструменты для работы с Git
- подсветка синтаксиса для множества популярных языков и файловых форматов
- удобная навигация
- встроенный предпросмотр Markdown
- умное автодополнение
- встроенный пакетный менеджер
VS Code имеет большое количество расширений для разработчика. Для установки нового пакета зайдите во вкладку “Extensions”, введите название пакета в строке поиска, нажмите кнопку “Install”.
EditorConfig for VS Code
EditorConfig — это конфигурационный файл и набор расширений к большому количеству редакторов кода. Он подхватывает настройки из файла .editorconfig , который, как правило, размещается в корне проекта. Расширение автоматически настроит отступы и перевод строк единообразно для всех разработчиков, использующих его. PHP код чаще всего выполняется на *nix системах, поэтому необходимо использовать стандарт.
Ниже приводится пример файла .editorconfig , который используется в Laravel:
PHP Intelephense
В редакторе уже есть поддержка синтаксиса и подсказок стандартных функций языка. Но без специального дополнения редактор не будет подсказывать пользовательские функции из других частей проекта. Поэтому для поддержки автодополнения, анализа кода, перехода к месту, где создана функция/класс/переменная (с помощью шортката Alt+Click ), используется дополнение PHP Intelephense
Чтобы подсказки не дублировались необходимо отключить встроенную в редактор поддержку кода для PHP: Extensions -> Search @builtin php -> PHP Language Features -> Disable
PHP Debug
При разработке может возникнуть ситуация, когда простых функций отладки и логирования становится недостаточно. Тогда может помочь специальный инструмент — Дебаггер. Для PHP есть расширение xdebug, которое позволяет расставить точки останова и посмотреть окружение в предполагаемом месте ошибки, выполняя код поэтапно либо до следующей точки.
Чтобы воспользоваться PHP Debug, необходимо установить сам XDebug, без него расширение для редактора работать не будет. Установив расширение, необходимо добавить конфигурацию для PHP в разделе Debug . После выбора языка в корне проекта будет создан файл .vscode/launch.json с задачами для Дебаггера. Расширение создаст файл со стандартными параметрами.
Для того, чтобы XDebug общался с нашим дебаггером, необходимо добавить настройки в файл конфигурации php. Чтобы найти этот файл выполните в терминале команду php --ini или запустите веб-сервер с кодом phpinfo() .
В Linux PHP подгружает не только основной файл, но и файл из этой директории. Например, на Ubuntu путь к директории конфигурационных файлов для PHP может быть таким — /etc/php/7.3/cli/conf.d/ . В ней создаём файл с необходимыми правами (требуются root права):
Это настройки для локальной разработки, когда проект разрабатывается и запускается на одном компьютере, например на вашей рабочей машине
PHP Sniffer
В языках программирования есть понятие стиль кодирования. Но не все разработчики знают об этом. Программа, которая отвечает за проверку на соответствие стандартам, называется линтер. В PHP приняты стандарты под названием PSR. Нас интересуют стандарты PSR-1 и PSR-12. Именно эти два стандарта касаются кодирования и правил оформления.
В PHP в качестве линтера используется PHP_CodeSniffer. Для его работы необходимо установить глобально сам линтер composer global require "squizlabs/php_codesniffer=*" и расширение PHP Sniffer.
Проверьте, что линтер установился:
Выполнить проверку кода в терминале можно с помощью команды phpcs , явно указав стандарт, который мы хотим использовать, и путь для проверки:
Semicolon Insertion Shortcut
PHP требует разделять инструкции с помощью точки запятой. Расширение Semicolon Insertion Shortcut добавляет необходимый символ в конец строки с помощью шортката. Если при нажатии [Ctrl] + ; символ не вставляется, то необходимо проверить список горячих клавиш и при необходимости назначить комбинацию вручную: File -> Preferences -> Keyboard Shortcuts
Extra
Список расширений, которые могут быть использованы не только для PHP:
-
— в VS Code уже встроена поддержка Git. Но когда базовых возможностей становится недостаточно, на помощь может придти Gitlens. Например, одна из полезных фич — git blame на текущей строке.
-
— разноцветные отступы в коде. Подсвечивает некорректный отступ. Можно вместо радуги установить оттенки серого.
Settings Sync — плагин, позволяющий синхронизировать настройки редактора между разными компьютерами. В качестве облачного хранилища используется Github Gists. Все настройки можно скачать, указав нужный файл синхронизации.
Fira Code — моноширинный шрифт, в котором используются лигатуры (объединяет несколько символов в один) для общих комбинаций символов в программировании. Визуальная надстройка для более удобного чтения кода.
Visual Studio Code is a great editor for PHP development. You get features like syntax highlighting and bracket matching, IntelliSense (code completion), and snippets out of the box and you can add more functionality through community-created VS Code extensions.
Linting
VS Code uses the official PHP linter ( php -l ) for PHP language diagnostics. This allows VS Code to stay current with PHP linter improvements.
Tip: Using XAMPP? Install the full version of PHP in order to obtain the development libraries.
There are three settings to control the PHP linter:
- php.validate.enable : controls whether to enable PHP linting at all. Enabled by default.
- php.validate.executablePath : points to the PHP executable on disk. Set this if the PHP executable is not on the system path.
- php.validate.run : controls whether the validation is triggered on save (value: "onSave" ) or on type (value: "onType" ). Default is on save.
To change the PHP settings, open your User or Workspace Settings ( ⌘, (Windows, Linux Ctrl+, ) ) and type 'php' to filter the list of available settings.
To set the PHP executable path, select the Edit in settings.json link under PHP > Validate: Executable Path, which will open your user settings.json file. Add the php.validate.executablePath setting with the path to your PHP installation:
Windows:
Linux and macOS:
Snippets
Visual Studio Code includes a set of common snippets for PHP. To access these, hit ⌃Space (Windows, Linux Ctrl+Space ) to get a context-specific list.
PHP extensions
There are many PHP language extensions available on the VS Code Marketplace and more are being created. You can search for PHP extensions from within VS Code in the Extensions view ( ⇧⌘X (Windows, Linux Ctrl+Shift+X ) ) then filter the extensions dropdown list by typing 'php'.
Disable built-in PHP support
To disable the built-in PHP smart completions in favor of suggestions from an installed PHP extension, uncheck PHP > Suggest: Basic, which sets php.suggest.basic to false in your settings.json file.
Debugging
PHP debugging with XDebug is supported through a PHP Debug extension. Follow the extension's instructions for configuring XDebug to work with VS Code.
Читайте также: