Visual studio code php
Visual studio code php
PHP in Visual Studio 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
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:
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.
Next steps
Read on to find out about:
Отладка php в Visual Studio Code (Xdebug, Windows)
В некоторых случаях может возникнуть необходимость отладки приложений на php. Visual Studio code предоставляет такую возможность при условии установки дополнительного расширения PHP Debug (marketplace, github).
Установка PHP Debug
Установка и настройка Xdebug
PHP Debug использует для отладки Xdebug. Для настройки Xdebug пройдите по ссылке. Предполагается, что на локальной машине уже установлен и настроен сервер apache. Здесь и далее действия указаны для Windows. Можно создать файл, например, test.php содержащий:
Открыть его в браузере и скопировать содержимое страницы в диалоговое окно. Другой способ:
Кроме этого, добавьте нижеследующие строки. Итоговое добавление будет примерно таким:
Как вы уже, возможно догадались, в данном примере на локальной машине установлен XAMPP.
Примечание: С версией Xdebug 2.5 и выше Visual Studio code не работает. Поэтому выбирайте соответствующий вашей версии php файл *.dll.
Настройка Visual Studio code
Вызовите панель отладки (1) и нажмите на иконку с маленькой шестеренкой (2).
Настройка PHP Debug на этом окончена.
Отладка php в Visual Studio code
Откройте в браузере ваше приложение\сайт. Откройте папку с приложением в Visual Studio code. Установите в нужных файлах и строках точки остановки. Откройте панель отладки и выберите для запуска отладки команду Listen for Xdebug (1). Нажмите кнопку запуска (2).
Обновите страницу в браузере и наслаждайтесь.
Настройка редактора Visual Studio Code для разработки на PHP
Пора перейти от слов к действиям и познакомиться с Visual Studio Code поближе. В этом посте представлена поэтапная настройка VS Code для разработки на PHP.
Скачайте и установите Visual Studio Code
После загрузки установите редактор на своем компьютере. Подробные инструкции по установке доступны здесь. Теперь можно открыть окно командной строки, запустить Visual Studio Code и начать редактировать файлы в папке.
Встроенные функции работы с PHP
VS Code поддерживает множество языков, в том числе PHP. На портале Visual Studio Marketplace доступны расширения VS Code, обеспечивающие поддержку дополнительных языков. Для PHP работает подсветка синтаксиса, определение парных скобок и фрагменты кода.
Когда вы начнете набирать код в файле PHP, то заметите автоматическое срабатывание цветового выделения синтаксиса, определения парных скобок и функции IntelliSense.
Настройка статического анализа PHP
По умолчанию VS Code будет проводить статический анализ кода на PHP в ходе проверки при сохранении файла. Для этого используется исполняемый файл php. Если вы работаете с VS Code впервые, то получите сообщение об ошибке, в котором сказано, что исполняемый 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.
Обратите внимание: это расширение использует отладчик XDebug. Поэтому для его работы необходимо установить XDebug. Скачать XDebug можно здесь (для Windows выбирайте 32-разрядную non-thread-safe версию).
Затем внесите в файл php.ini следующие настройки. Я установил XDebug в подкаталог ext установочной папки PHP. Если вы выбрали для XDebug другой каталог установки, убедитесь, что параметр zend_extension содержит правильное значение.
Убедитесь, что корневой раздел веб-сервера соответствует вашему проекту. Тогда при каждом запросе файла 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.
PHP Debug
Xdebug
PHP Debug Adapter for Visual Studio Code
Sponsored by
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 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:
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:
There are other ways to tell Xdebug to connect to a remote debugger, like cookies, query parameters or browser extensions. I recommend remote_autostart (Xdebug v2)/ start_with_request (Xdebug v3) because it «just works». There are also a variety of other options, like the port, please see the Xdebug documentation on remote debugging for more information. Please note that the default Xdebug port changed between Xdebug v2 to v3 from 9000 to 9003.
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:
There are also configurations for Xdebug v2 (Legacy) installations.
More general information on debugging with VS Code can be found on https://code.visualstudio.com/docs/editor/debugging.
Supported launch.json settings:
Options specific to CLI debugging:
Features
Remote Host Debugging
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
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.
Настройка Visual Studio Code для разработки PHP
Visual Studio Code (или просто VS Code) – бесплатный редактор исходного кода или интегрированная среда разработки (IDE), доступная для всех основных операционных систем.
Благодаря большому набору расширений VS Code можно легко настроить для удовлетворения самых разнообразных потребностей разработки. В этом руководстве вы узнаете, как настроить Visual Studio Code для работы над проектами PHP.
Требования
Чтобы следовать этому руководству, вам необходимо загрузить и установить соответствующую версию Visual Studio Code для вашей операционной системы.
Инструкции в этом руководстве были проверены на настольном компьютере Ubuntu 20.04, но они должны без проблем работать и в других операционных системах, поддерживаемых VS Code. Однако обратите внимание, что в системах MacOS сочетания клавиш могут немного отличаться.
1: Установка PHP-расширений VS Code
VS Code распознает PHP-код и помогает с подсветкой синтаксиса, базовой отладкой и отступами кода сразу же после установки. Этого вполне достаточно для быстрого редактирования или для работы с отдельными сценариями PHP. Однако более крупные проекты сложно обслуживать без дополнительного контекста вокруг кода и без наглядного понимания того, что делает каждый файл и как он интегрируется в проект.
Существует ряд расширений VS Code, которые помогут повысить вашу продуктивность при работе над проектами PHP. В этом руководстве мы установим и настроим PHP Intelephense, популярное расширение PHP для VS Code, которое предоставляет несколько дополнительных функций: улучшенное автозаполнение кода, навигацию между компонентами, всплывающие подсказки с полезной информацией при наведении курсора мыши, автоматическое форматирование кода и создание отчетов об ошибках в реальном времени на основе статического анализа кода.
Откройте вкладку расширений, нажав на последний значок в левой строке меню или клавиши CTRL+SHIFT+X. Это вызовет меню боковой панели с полем поиска и списком популярных или рекомендуемых расширений. Введите «php» или «intelephense», чтобы найти нужное нам расширение PHP Intelephense. Затем нажмите кнопку Install, чтобы установить и включить расширение.
Официальная документация Intelephense рекомендует после завершения установки отключить встроенное расширение PHP Language Features, которое поставляется с VS Code.
Чтобы сделать это, введите @builtin php в поле поиска расширений. Когда вы найдете его, нажмите на значок настроек для расширения PHP Language Features и выберите параметр Disable в выпадающем меню.
Если в VS Code у вас есть открытые файлы, вам необходимо перезагрузить редактор, чтобы изменения вступили в силу.
Вы можете установить другие расширения, следуя описанному выше процессу, но имейте в виду, что некоторые расширения потребуют установки дополнительного программного обеспечения в вашей системе. Проверьте документацию по интересующему вас расширению, чтобы убедиться, что у вас установлены соответствующие зависимости.
2: Импорт или создание нового проекта PHP
Чтобы импортировать существующий проект PHP в VS Code, нажмите на первый значок в левой строке меню или клавиши CTRL+SHIFT+E – так вы сможете получить доступ к проводнику файлов. Нажмите кнопку Open Folder и выберите каталог своего проекта. Если вы создаете новый проект, вы можете создать новую папку и выбрать ее в качестве каталога вашего проекта.
В окне проводника теперь будет отображаться дерево каталогов проекта, что даст вам быстрый доступ к необходимым файлам и каталогам.
3: Настройка темы и шрифта редактора (опционально)
В настройке внешнего вида редактора нет острой необходимости, но иногда это бывает полезно – так можно сделать его более удобным для работы в долгосрочной перспективе. Разработчики много времени проводят в IDE (чем и является VS Code), и по этой причине важно убедиться, что шрифт редактора имеет соответствующий размер, что контрастность не утомляет глаза слишком быстро и код удобно читать.
Что касается удобочитаемости, здесь нет единой рекомендации. Советуем вам самостоятельно поэкспериментировать с разными темами и шрифтами, чтобы подобрать настройку, которая вам подходит.
Изменение темы VS Code
VS Code поставляется с несколькими темами, которые позволяют изменять цвета, используемые в интерфейсе редактора и при выделении кода. По умолчанию включены темный и светлый стили.
Также можно установить расширения для темы, чтобы дополнительно настроить внешний вид VS Code. Если вы выполните поиск (CTRL + SHIFT + X), вы найдете несколько расширений для темы с разными стилями и цветами, включая цветовые схемы, перенесенные из других популярных редакторов и платформ.
Настройка шрифта
В целом, настройки шрифтов VS Code по умолчанию достаточно хороши – многие пользователи предпочитают не менять их. Но если вы хотите, вы можете настроить размер и тип шрифта редактора для повышения удобочитаемости.
Изменения немедленно сохраняются и применяются ко всем текущим открытым файлам.
Заключение
Visual Studio Code – это легкий, но мощный редактор кода, который можно настроить в соответствии с потребностями большинства разработчиков. В этом руководстве вы узнали, как установить и настроить расширение PHP Intelephense для работы над проектами PHP, как импортировать и создавать новые проекты в VS Code и как настроить внешний вид редактора, чтобы сделать процесс разработки более удобным.
PHP Tools
DEVSENSE
PHP Tools for Visual Studio Code
PHP Tools for VS Code is a full development integration for the PHP language. The features are provided respecting conventions, stability, simple use, and performance. Please see the product page for more details on devsense.com.
This package extends VS Code with fast code completion, advanced editor features, code fixes, code lenses, code generators, debugger, built-in development web server, test explorer, tests debugger, and workspace-wide code analysis.
Support for vscode.dev
Editor
Debugging
Code Analysis
Testing
Code Help and Completion
Take advantage of type-based, blazing fast code completion, signature help, and colorful tooltips within VS Code. The editor is context-aware, lists available symbols with detailed information, performs type analysis, and completes selected options. It also auto-completes the dollar character for variables and even provides a URL to online documentation when possible.
Code Actions
Quickly refactor and generate code using code actions. This feature gives you quick fixes for the code that is right at your cursor, at your hand. Generate PHPDoc, property getters and setters, implementation of interfaces, abstracts, and more.
Debug
Run the integrated built-in server, debug a script, or connect to a local or a remote server. Debug is provided through Xdebug extension and provides you with all you need. Easy to use with the respect to VS Code conventions. See and manage breakpoints, watch expressions, locals, the call stack, or change variables value. Tooltips reveal the expression’s value as well, including subsequent listing through large arrays.
Continuous Code Validation
Reveal troublesome issues and problems without testing, and even before running the code. The built-in type analysis and code validation will check the entire project in seconds, and it gets updated as you type. Problems are listed in the Problems window and underlined right in the code editor.
Navigation
Rename Refactoring
Safely find and rename variables, classes, interfaces, or functions with a single press of a key. The feature takes into account PHPDoc comments, possible indirect variables, or dynamic code constructs.
Code Formatting
The formatter makes the code look clean and unified. It understands your conventions, keeps multiline expressions as you wrote them, adjusts the comment blocks, pretty prints the expressions and nicely purifies the rest. Code is formatted automatically when you finish the statement or a code block.
Testing
PHPUnit tests within the project are detected and automatically listed in the Test View panel. You can run and debug all the tests, a suite, or just a single one. All the listed tests are marked with the succeeded icon with details of the test run. Failures are inlined in the code with the corresponding diff. See the testing documentation for more details.
Related links
Notices
The extension is based on MIT licensed code and is subject to the following notice:
The embedded language feature is based on work of Ben Mewburn and is subject to following notice:
Copyright (c) Ben Robert Mewburn Licensed under the ISC Licence.
The software’s debug protocol library is based on MIT licensed code and is subject to following notices:
Copyright (c) Microsoft Corporation All rights reserved. MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the «Software»), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
MIT License Copyright (c) 2016 Felix Frederick Becker Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the «Software»), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
The software’s test explorer is based on MIT licensed code and is subject to following notices:
The MIT License (MIT) Copyright (c) 2018 Holger Benl hbenl@evandor.de Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the «Software»), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
Copyright (c) 2001-2018, Sebastian Bergmann sebastian@phpunit.de. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of Sebastian Bergmann nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS «AS IS» AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The MIT License (MIT) Copyright (c) 2008 Ricardo Amores Hernández
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the «Software»), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
PHP in Visual Studio 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
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:
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.
Next steps
Read on to find out about:
Setup VS Code for Efficient PHP development 🚀
I recently started programming in PHP using the well-known Symfony framework. I wanted to keep my VS Code habits and proficiency I had from my previous projects in Node.js and Vue.js, so I tried to configure VS Code for PHP development as well. Moreover, I didn’t want to invest €199 in the famous PHPStorm IDE… 😕
VS Code extensions you should install and configure for PHP development:
In this article, I will explain how I managed to make my development environment comparable to PhpStorm’s. The commands will be detailed for Ubuntu 18.04, but they can be adapted for Mac OS and possibly for Windows.
I will take an empty Symfony application as an example for this article. Let’s start!
Prerequisites
Install PHP and Composer
To be able to run PHP code you obviously need to install PHP. You will also probably need Composer, a commonly used dependency manager for PHP. You can install them by running the following command:
You can install php-all-dev instead of php-cli if you want to install some useful libraries as well.
Create an empty Symfony project
Let’s now create an empty Symfony app. Then open VS Code and launch the development server:
Increase the number of system watchers if needed
VS Code needs to watch for file changes to work correctly. That’s why the following warning may appear because our Symfony project contains a lot of files:
To fix it, you can run the following commands in your terminal, and then restart VS Code:
Go to http://127.0.0.1:8000 from your favorite web browser and check that your Symfony website works.
Configure VS Code for PHP
Autocomplete & Intellisense & Go to definition
Let’s create a new route in our application. Just add an empty file HelloWorldController.php in the src/Controller folder.
Install PHP Intelephense
By default, VS Code provides some basic code suggestions but they are generic and quite useless. To get useful code suggestions as you type, I recommend installing the PHP Intelephense extension for VS Code. I also tried the PHP Intellisense extension but it’s slower on big projects and provides fewer features (it doesn’t gray out unused imports for example).
Now that the PHP Intelephense extension is installed, we can start writing our HelloWorldController!
As you can see, code suggestions are very relevant and VS Code auto imports the corresponding namespace when you validate a suggestion!
Disable basic suggestions
Basic PHP code suggestions we want to disable
When it’s done, you can see useful suggestions!
Relevant suggestions when basic suggestions are disabled
Enable autocomplete in comments / annotations
When you write PHP code, a good practice is to add PHPDoc annotations to make your code more understandable and to help your IDE provide you with relevant code suggestions. By default, VS Code doesn’t suggest anything while writing annotations. To activate code suggestions in comments, open the settings.json file and add the following line:
Code suggestions in annotations
Allow autocomplete in tests
By default, PHP Intelephense excludes Symfony test folders from indexing because the default exclude settings contains a too generic pattern:
To enable suggestions for Symfony test classes, all you need to do is edit your settings.json file and add:
As you can see, the last line is more specific than in the default settings.
Code completion enabled for tests
Go to definition
When you want to get more information about a function, you can Ctrl+Click on it and VS Code will open the line where the function is declared!
Generate getters and setters for class properties
If you want VS Code to generate getters and setters for you, you can install this extension. Then, right-click on a class property and select Insert PHP Getter & Setter.
Generate getter and setter
Debugging
Debugging your PHP code can be painful without a debugger. You can use dump($myVar); die(); (😕) but it’s not very convenient.
The best way to debug your PHP code is to use Xdebug, a profiler and debugger tool for PHP.
Install Xdebug
Xdebug is not shipped with PHP, you need to install it on your development environment:
Then run sudo nano /etc/php/7.2/mods-available/xdebug.ini and add the following lines:
Tip! If your PHP project runs in a Docker container, you need also to add the following line to the xdebug.ini file, where 172.17.0.1 is the IP address of the docker0 interface on your computer (on Mac OS you have to put host.docker.internal instead):
Configure VS Code debugger to listen for Xdebug
To be able to use Xdebug in VS Code, you need to install the PHP debug extension.
Then go to the debug tab in VS Code (accessible in the side menu) and click on Add configuration. Select PHP, and close the newly created launch.json file:
Configure VS Code debugger to listen for Xdebug
Tip! If your PHP project runs in a Docker container, you need to add the following path mapping to the launch.json file in the Listen for Xdebug section:
Your debugging environment is now ready! 🕷🚀
Debug your code with VS Code
Let’s debug our HelloWorldController.php to see which are the query parameters given by the user. You can use the following code for example:
Press F5 in VS Code to start the debugging session.
Uncheck the _Everything _option in the breakpoints list and put a breakpoint at line 18 by clicking left of the line number. Then go to http://127.0.0.1:8000/hello?name=Louis. You can now see the value of local variables by hovering the mouse pointer over them:
You can do a lot of amazing things with the debugger 😃, like:
For more information about the power of VS Code debugger, you can visit the official website.
Configure Xdebug to open file links with VS Code
When you encounter an error, or when you use the Symfony debug toolbar or the profiler, you may want to open the desired file directly in your IDE with the cursor at the corresponding line.
To be able to do that, you need to add the following line to your /etc/php/7.2/mods-available/xdebug.ini :
Tip! If you run PHP in a Docker container, you can specify a path mapping between your host and your docker like this:
Now, when an error occurs, you can click on it and go directly to the corresponding line in VS Code:
When you visit a route, you can also jump to the corresponding controller by clicking on the debugging toolbar:
Formatting & linting
Formatting and linting your code is a very good practice to keep it clean automatically, and to inform you about some errors.
PHP CS Fixer
The best and commonly used linter for PHP is PHP CS Fixer. It provides a large number of rules to keep your code clean. You can visit this website for more information about the rules and the categories they belong to.
Integrate PHP CS Fixer into VS Code
To be able to auto-format your PHP files in VS Code, you need to install the php cs fixer extension.
The most complete and safe category of rules is @PhpCsFixer. It’s a good point to start. To enable this set of rules in VS Code, open settings.json and add the following line:
To auto-format your PHP files on save, you also need to add the following lines to your settings.json :
Auto-format on save with PHP CS Fixer
PHP CS Fixer config file
Bonus: add Prettier to PHP CS Fixer
Prettier for PHP is a code formatter which makes some improvements that PHP CS Fixer does not do. It allows you, among other things, to configure a max line length and makes your code even cleaner.
To add Prettier for PHP to your PHP CS Fixer configuration, you can follow these instructions.
In case of issues with format on save
Depending on your computer’s speed, the length of your files and the number of rules you activate, linting a file on save can be slow, causing VS Code to refuse it. To fix this behavior, change the formatOnSaveTimeout in your settings.json :
Twig support
To activate syntax highlighting for Twig files in VS Code, you need to install the Twig Language 2 extension.
To enable emmet suggestions like in HTML files, add the following line to your settings.json :
Database management
A good VS Code extension to manage your databases is SQLTools. Feel free to install it and manage your databases directly from your IDE!
Enjoy coding in PHP with VS Code 🚀 and feel free to give me your feedback! 😉
Want to learn more about how Theodo can help bring your Symfony project to the next level? Learn more about our team of Symfony experts.
Visual studio code php
Visual Studio Code is one of the best free text editors out there. Right out of the box, Visual Studio Code offers basic PHP support but nothing more than that. To enjoy a fruitful PHP development, you need to install PHP extensions. Today, I am going to highlight 5 extensions you might want to consider. If you would like to try out Visual Studio Code, you can download it here.
PHPCS (PHP CodeSniffer) – Ioannis Kappas
This extension offers an interface for PHP CodeSniffer. PHP CodeSniffer scans the PHP files in your workspace to detect and offer suggestions and fixes for violations of a defined set of PHP standards. It’s an excellent extension that will ensure you strictly follow standard for PHP.
You can learn more about PHP standard here. For you to use this extension, you need to install PHP CodeSniffer globally into your development machine. You can install PHP CodeSniffer using either PEAR or Composer as shown below.
To install PHPCS, press F1 on Visual Studio and type the following command:
You can learn more about this extension here.
PHP Intellisense Crane – Hvy Industries
To use the creator’s words, PHP Intellisense Crane is a productivity enhancement extension for Visual Studio Code that provides code-completion for PHP. It has zero dependencies and largely works with projects of any size. The extension is active in development and you can raise issues and make feature suggestion on GitHub. This extension offers the following features: Code Completion, Go To and Peek Definition on classes, interfaces and traits and document workspace symbol provides. To install PHP Intellisense Crane, press F1 on Visual Studio Code, and type the command below.
Once installation is complete, wait for it to parse all PHP files in your workspace. You will see a progress bar at the status bar.
You can learn more about PHP Intellisense Crane here.
PHP Intelephense – Ben Mewburn
This is one of the best PHP Extension I have ever used. It provides a tonne of useful features without affecting negatively the performance of Visual Studio Code. It also has no external dependencies. It has the following features:
To install this extension, press F1 and type in the command below:
You can learn more about this extension here.
PHP Intellisense – Felix Becker
Just like the name suggests, it offers Intellisense autocompletion for PHP. This extension depends on PHP Language Server to work. The extension just provides an interface to the PHP Language Server. To use this extension, first install the PHP Language Server using composer as show below:
If you have multiple projects, you can install PHP Language Server globally as follows:
You also need to have PHP7 installed in your system. Then go ahead and install the extension on Visual Studio Code. Press F1 and type in the following command:
You can learn more about the extension here.
PHP Debug – Felix Becker
This extension is an adapter for XDebug extension for PHP. XDebug is an extension for PHP that assists with debugging and development of PHP projects. To use this application, you need to install XDebug and PHP into your system.
You can follow the instruction found in the extension page here. To install this extension, press F1 and type in the command below.
PHP Intelephense
Ben Mewburn
Intelephense
PHP code intelligence for Visual Studio Code.
Intelephense is a high performance PHP language server packed full of essential features for productive PHP development.
Licence
Purchase a licence at https://intelephense.com to access PREMIUM features. Licence keys grant a single user access to all current and future premium features on multiple devices forever. Licence keys must be activated (automatically) via https before use. Features not marked as PREMIUM are free and always will be free.
The language server client (vscode-intelephense) is open source and licensed under the MIT licence.
The language server (intelephense) is proprietary. Please see here for details.
Quick Start
Disable the built-in VSCode PHP Language Features.
Note that other (3rd party) PHP extensions which provide similar functionality should also be disabled for best results.
Add glob patterns for non standard php file extensions to the files.associations setting.
For example: «files.associations»: < "*.module": "php" >.
Further configuration options are available in the intelephense section of settings.
Support
Found a bug? Got a feature request? Create an issue.
Acknowledgements
A big thank you to supporters who have bought a premium licence and have enabled the continued development and maintenance of this extension.
Intelephense uses the following open source libraries. Please see the following links for source code and licences.
PHP 8 in Visual Studio Code
PHP 8 represents a big milestone for developers, frameworks, and content management systems like WordPress. It introduces several new language constructs, that are not backward compatible with previous versions of PHP, it deprecates some functions, and there are some new eventual issues you should be aware of.
The Environment
When developing with VS Code, you have to install PHP and Xdebug by yourself. In case you are running Windows and Microsoft Visual Studio, there is our One-Click installer for PHP.
To specify which PHP version should be used by the Visual Studio Code editor, change the VS Code’s setting «php.executablePath» to point to the binaries. On Windows, it might be something like:
Named Arguments
Named arguments is a new PHP 8 feature allowing to specify the name of parameter before provided the value. It allows to skip optional parameters, makes the code more readable, and also it works great with argument unpacking and call_user_func_array() function.
In Visual Studio Code, it is well understood by code completion, tool-tips, and code analysis as well. Misspelled arguments are underlined, since it would cause a fatal error in run time, type mismatches are checked as well. In case, user doesn’t have PHP 8, any use of named arguments is underlined as well, since it is considered a syntax error on PHP 7.4 or older.
Code completion provides available arguments including the detailed tool-tip information with type, default value, and description.
Attributes
There are a few nice syntactic sugar enhancements, that might make your code smaller and more readable.
The Editor
The Visual Studio Code editor with PHP Tools respects and helps with the new PHP 8 features, including the new Xdebug 3 debugging extension support and other language constructs like the new union type hints and checking for compatibility if you haven’t switched to PHP 8 yet and still using the version 7.4. Our integration is getting more updates soon, always keeping up to date with the latest standards.
How to install PHP Tools for Visual Studio Code on Windows
In this article, you will find out how to install PHP Tools for VS Code on Windows. Getting it running is fast and simple and it shouldn’t take you more than a few minutes.
Install Visual Studio Code for Windows.
To install PHP Tools, you need to have Visual Studio Code (VS Code) already installed on Windows. For those who already have it, just skip this step. For those who don’t, download VS Code for Windows. If you would like detailed instructions, click here.
Once you have VS Code installed, you have different ways of installing PHP Tools. In this article, we’ll discuss two ways: The internal installation directly from VS Code, and the external from Devsense’s download page. Both ways are simple, fast and easy.
Internal Installation
Click the icon for extensions.
Search for “PHP Tools” in the search menu.
Click Install. The tool should be installed automatically.
After the successful installation, a pop-up window will appear on the bottom right of the screen.
There, you’ll have to choose among entering your license key, choosing to get a trial or receiving more information. Please, refer to the Activation section of this tutorial for detailed instructions.
External Installation
Make sure you have selected the section for VS Code on the right (the letters should be blue).
Click the blue button “Get the extension” under the version you would like to download.
Install from VSIX
Open the command palette on VS Code ( Ctrl + Shift + P ) and type in “Install from VSIX”. Next, click Install.
Activation
After successfully installing PHP Tools for VS Code, you’ll receive a notification on the bottom right to activate it. Please, bear in mind that the activation of the software requires an Internet connection. You’ll see three buttons:
a. “I have the license key”
If you already purchased your license key, click that button and fill in the required information.
If you would like to try PHP Tools for VS Code, click this button:
Fill in the information and you’ll receive an email with a 14-day trial key. Copy and paste the key and you’ll be able to start using the tool. If you think PHP Tools for VS is the right option for you, you can purchase a license after the trial period is over.
c. “More information”
This button will take you to the purchase page, where you’ll see prices and license information.
The activation will be confirmed by a pop-up window stating that the process was successful.
Debugger and configuration
Once you have activated your PHP Tools, you need to setup PHP Tools’ debugger. PHP Tools makes use of Xdebug to integrate debugging features into VS Code.
PHP Tools plugin doesn’t require you to have a web server! Only PHP. There are two options to install PHP on your platform.
a. You can go to php.net and download the installer of the latest PHP by yourself (preferred).
b. You can download the whole web server package for PHP – Xampp or Wamp.
Copy the whole content of phpinfo() that shows up and go to the Xdebug Wizard. Insert the copied content there and click on the highlighted button below.
When you’re done with the above-mentioned steps, the last thing to do is ensure php.ini states the following directives:
Now you are ready to start your first project!
How to run or debug php on Visual Studio Code (VSCode)
I can’t find a way to run or debug php on Visual studio code, Does anyone know how?
11 Answers 11
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Debugging PHP with VSCode using the vscode-php-debug extension
VSCode can now support debugging PHP projects through the marketplace extension vscode-php-debug.
This extension uses XDebug in the background, and allows you to use breakpoints, watches, stack traces and the like:
Installation is straightforward from within VSCode: Summon the command line with F1 and then type ext install php-debug
As far as I read about it today, you can’t debug anything else than node.js, JavaScript and TypeScript at the moment, but they said they want to add new languages which you can debug. The editor is still in development. Nevertheless, I don’t think there will be a php debugger in the future since php is serverside, so you can’t debug it on your client alone.
If you want to debug php, I can recommend xDebug.
Updated:
Now, it is possible to debug with VS code. You need to install XDebug and php-debug extension for VScode.
From the link, the steps are:
Note there are specific details in the linked article, including the PHP values for your VS Code user config, and so on.
There is a much easier way to run PHP, no configuration needed:
Besides, you could select part of the PHP code and run the code snippet. Very convenient!
If you don’t want to install xDebug or other extensions and just want to run a PHP file without debugging, you can accomplish this using build tasks.
Using Build Tasks (No extensions required)
First open the command palette ( Ctrl + Shift + P in Windows, ⌘ + Shift + P in Mac), and select «Tasks:Open User Tasks». Now copy my configuration below into your tasks.json file. This creates user-level tasks which can be used any time and in any workspace.
If you want to run your php file in the terminal, open the command palette and select «Tasks: Run Task» followed by «Run In Terminal».
If you want to run your code on a webserver which serves a response to a web browser, open the command palette and select «Tasks: Run Task» followed by «Start Server» to run PHP’s built-in server, then «Run In Browser» to run the currently open file from your browser.
Note that if you already have a webserver running, you can remove the Start Server task and update the localhost:8080 part to point to whatever URL you are using.
Using PHP Debug
Note: This section was in my original answer. I originally thought that it works without PHP Debug but it looks like PHP Debug actually exposes the php type in the launch configuration. There is no reason to use it over the build task method described above. I’m keeping it here in case it is useful.
Copy the following configuration into your user settings:
This creates a global launch configuration that you can use on any PHP file. Note the runtimeExecutable option. You will need to update this with the path to the PHP executable on your machine. After you copy the configuration above, whenever you have a PHP file open, you can press the F5 key to run the PHP code and have the output displayed in the vscode terminal.
ForEvolve
Buy My Book Amazon (associate link)
Buy My Book Amazon (associate link)
Buy My Book Amazon (associate link)
Buy My Book Amazon (associate link)
PHP with Visual Studio Code and XDebug
Introduction
In my introductory class to server-side programming with PHP and MySQL, I need a code editor or a full-featured IDE. Usually I go with NetBeans, but this year i decided to give the new cool kid a shot, so i picked : Visual Studio Code. Before officially choosing anything, I had to test its capabilities.
Here is what I am looking for:
My conclusion: VS Code covers most of my expectation for an introductory class code editor. The only problem is that, as of today, the PDO Intellisense is only partly covered and pretty close to 0%. Let this be a subject for another day.
In the current tutorial:
That’s a lot of stuff, so lets get started…
Installing PHP & MySQL with MAMP
Before coding in PHP, you need PHP installed and before connecting to MySQL, you need MySQL installed as well. Pretty obvious right?
For easy installation, I recommend WAMP or MAMP. I usually go with WAMP, but let’s try MAMP today since it is compatible with both Windows and OS X.
Installing MAMP
Its pretty straight forward, you download the installer, click next, next, next and it is installed. I unchecked the Pro Version checkbox since I do not plan to buy it. If you do plan on doing a lot of PHP development, it might be a good idea to take a look at the MAMP Pro version, its only about 80$ CAD (well, that’s up to you).
Configuration
Now that MAMP is installed, lets open it. It is a nice clean and minimalist window with a few options in it: Preference, Open start page and Start Servers.
If you see the following error message, don’t worry you can easily change the port number by configuring MAMP.
As we are heading toward configuring our environment, lets click the Preferences… button.
Start/Stop
In this tab, there is some basic options, that are pretty self-explanatory.
Ports
This is the tab to use to change port numbers.
Due to a conflict with IIS Express, I need to change my Apache port to 8080. Skype also cause conflict some times, so if you have Skype installed, that might be the cause of the problem. If MAMP did not alert you of a port conflict, you don’t need to change anything so you can skip this part.
After updating MAMP Apache port number, I found out that I also needed to update my Apache httpd.conf file as well. You may also need to restart MAMP if something seems wrong.
Update Apache port number
We wont use PHP 7, so I will change the version to 5.6.21.
Web Server
We wont touch this.
Testing our installation
Back on the main window, if we click “Open start page” it should open the start page. I love when software’s are that self-explanatory!
If the page does not open or if there seems to be a problem, try to restart your MAMP (or the servers: “stop servers” then “start servers”).
Setting up Visual Studio Code
Now that we have MAMP up and running, lets install our code editor. First head to https://www.visualstudio.com/ and download “Code”. Make sure you pick Code, not Visual Studio Community, that is a totally different product.
Run the installer, again its a pretty straight forward installation.
How to install plugins
Now that we have installed our code editor, we will need to install the following plugin:
Since June update there is a plugin “tab” with a search box. The small number (3 in the screenshot) is the number of plugins that have available updates.
VS Code folder
In code, a project is named a folder, so you basically open a directory and work with it.
Lets create our PHP project.
See The Basics of Visual Studio Code for more info about Visual Studio Code.
This is my project structure (i choose this directory structure to show you how to start the PHP server within a sub-directory):
PHP development server
Now that we have an opened folder and a PHP page that we want to see in a browser, we still have a few things to do to make it work out.
Tell Code where is PHP
To do that, we need to alter our configuration. I decided to go for “User settings”, this way it will be done for all of my projects. It is also possible to have different settings per project, but lets just focus on User settings for now.
Settings, in Code, use the JSON format which is flexible and easy to manage (and human readable).
For more info on Code and PHP, see PHP Programming in VS Code.
Opening a console
To start our server, we will need a console. To do that, go to View > Integrated terminal. You can even have multiple consoles open at the same time.
Copy/paste
In the console, ctrl+c and ctrl+v are not yet supported. To copy/paste you need to use these shortcut instead:
Starting the server
In the console, we will tell PHP to start a development server in our www sub directory by typing the following command:
If you visit http://localhost:8000/ in a browser, you should see the content of your index.php file.
Breaking down the command
For a folder without sub-directories, where index.php is at the root (see screenshot below), you can run this command instead:
Setting up XDebug
Now that we have everything setup, lets connect XDebug to Code.
Lets write some PHP and create a breakpoint
Lets add a bit of PHP in our index.php file (we need something to test our connection):
If you don’t know what a breakpoint is, just create one anyway and you will soon discover what it does.
Configure PHP to enable XDebug
Your PHP directory should now look like this:
Inside the php.ini file
In this file you can control how PHP does things. I wont go deep into it, but if you are interested, you can easily find tons of info by googling a bit.
We want to add the following code at the bottom of php.ini :
When you do configuration changes, if you have a running PHP development server, you need to restart it. To do so, in the console, hit Ctrl+C to stop it, then up arrow to write your last command back, then press enter to execute it.
Create the launch.json file
Your launch.json file should look like this:
The port must be the same in both launch.json and php.ini files.
Manually starting a XDebug session
If you try it, your code should break in Code at line 2 of your index.php file.
For more info on XDebug, you can take a look at their website or at Debugging and Profiling PHP with Xdebug.
Google chrome extension
If you are like me and don’t like to remember those kind of things and that don’t want to bother about navigation and all that stuff, you will find the following Chrome extension very handy: xdebug-helper.
It add a little “bug” icon. When you click on it, it shows you a few options including “Debug” (which start a debugging session) and “Disable” (which end the debugging session).
There is multiple ways to start an XDebug session, the plugin use cookies instead of querystrings.
Conclusion
Now that we are done, lets recap on what we achieved:
Now that everything is connected, we can write some PHP and debug it using Visual Studio Code!
xdebug/vscode-php-debug
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
PHP Debug Adapter for Visual Studio Code
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.
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:
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:
There are other ways to tell Xdebug to connect to a remote debugger, like cookies, query parameters or browser extensions. I recommend remote_autostart (Xdebug v2)/ start_with_request (Xdebug v3) because it «just works». There are also a variety of other options, like the port, please see the Xdebug documentation on remote debugging for more information. Please note that the default Xdebug port changed between Xdebug v2 to v3 from 9000 to 9003.
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:
There are also configurations for Xdebug v2 (Legacy) installations.
More general information on debugging with VS Code can be found on https://code.visualstudio.com/docs/editor/debugging.
Supported launch.json settings:
Options specific to CLI debugging:
Remote Host Debugging
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.
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.
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.
How To Use PHP In Visual Studio Code
Visual Studio Code is a great editor for PHP and other language development. You get almost all the features like syntax highlighting, bracket matching, PHP IntelliSense, and snippets out of the box, and you can create or add more functionality through community-created Visual Studio Code extensions.
Sure, there are quite some commercial applications like phpStorm that can help with debugging PHP code. But these business applications are usually very expensive and operating system dependent. Luckily there are a few open-source code editors out there that will give PHP developers the same debugging experience without expensive IDEs, and VS Code is one of them.
If you are new to VSCode, check out how to install visual studio code on mac. That guide will help you to set up the VSCode in your Mac.
How To Use PHP In Visual Studio Code
By default, Visual Studio Code comes with PHP Support, but you can also install the PHP language extensions available on VS Code Marketplace. You can search for the PHP extensions from within the VS Code in the Extensions view ( ⇧⌘X ), then you can select the extensions using a drop-down list by typing php. But first, check your PHP version using the following command.
I have PHP version 7.2.11, and if you have something like 5.6.* or 7.0.* or 7.1.* then it is good to update your PHP version. I have installed PHP using homebrew, so I can update the PHP version using the following command. This PHP version upgrade guide is for MAC and not for Windows.
If you are using MAMP or XAMPP, then you need to update that software bundle as well to get the latest PHP version.
PHP extensions for VSCode
PHPIntelliSense and PHP Debug are the most IMP extensions for PHP Development Environment. But there are more extensions that you can use based on your project flow or your style to write the code. Extensions will help you to fast your workflow and reduce your code repetition and also provide code completion.
PHP IntelliSense
Please find your PHP Executable and do not copy the above code if you have a different PHP version and the way you have installed PHP previously because PHP’s path will be changed on your machine. For example, if you are using MAMP or XAMPP, then the php path is different. However, I have used Homebrew so that I can write the above path.
Features Of Intellisense
PHP Debug
Install the extension: Press F1 and type ext install php-debug.
This extension is the debug adapter between the VS Code and XDebug by Derick Rethan. XDebug is the PHP extension (a .so file on Linux and a .dll on Windows) that needs to be installed on your server.
Features Of PHP Debug
PHP Code Linting
There are three settings to control the PHP linter:
Finally, How To Use PHP In Visual Studio Code article is over.
PHP in Visual Studio Code: Your first PHP project
Table of Contents
In this tutorial you will start your first PHP project. I always use PHP in Visual Studio Code, so it is best if you use Visual Studio Code, as your coding editor.
Preparing to Start
First, we need to find the “htdocs” folder in the XAMPP installation (we use XAMPP, as our PHP environment).
Usually, if you have installed XAMPP by its default settings, you will find “htdocs” folder in the following path:
Again, your’s might be in a different location.
Once, you find the htdocs folder, you will need to create a new folder there.
I have named mine: “PHPinVisualStudioCode”.
With the project folder created, we now open our code editor, which is (you’ve guessed it 🙂 Visual Studio Code.
PHP in Visual Studio Code
First, we need to locate our project folder and open it in Visual Studio Code.
Now, the folder is linked and we can access it from Visual Studio Code.
Creating e new PHP file
To create a new file, Right Click in the “Explorer” section of Visual Studio Code (inside the folder) and hit “New File”. Or, you can click the new file icon:
I will name my file “index.php”. You can name it as you wish, but make sure you save it with the “.php” extension.
This is a must follow procedure, otherwise your PHP file will not be executed by the Apache Server.
The “.php” extension lets the Apache server know that this file has PHP code in it, that needs to be executed.
Next, we open the file and we are ready to start coding.
Your First PHP Project
In the opened file, we first open the PHP tags, by typing:
Next, we call the “phpinfo()” function and don’t forget to add a semicolon (;), to end the line.
Lastly, we close the PHP tag by typing:
And here is the final code:
Running your first PHP Project
To be able to run your first PHP project, created in Visual Studio Code, you need to have the Apache Server up and running.
It can run locally (using XAMPP) or in your hosting environment.
In XAMPP, to make sure the Apache server is running, make sure that the “Start” button is clicked in the “Actions” column in the XAMP Control Panel and the “Apache” word has a green background.
You can activate the XAMPP control panel from the XAMPP installation folder. Find the “xamp-control” application icon and double click it.
In my XAMPP installation the XAMPP control panel is located at this path:
View your first PHP Project in Browser
With Apache server running, open your desired web browser.
In the url box, type the location to your PHP project and your PHP file and hit “Enter”.
I saved mine in this path:
The “localhost” part, shows you that you are running the Apache server locally.
The part “PHPinVisualStudioCode” is the folder name.
The part “index.php”, is the PHP filename.
Running this PHP file, will show you the PHP installation information (that is what the phpinfo() function does).
If you don’t see a screen like the one below, then something went wrong. You should check your Apache server or your PHP code.
Another Example
You can go back to your “index.php” file and type this code:
The code above, will print the line “Hello there!” in your browser!
Conclusion
And here you go, congratulations, you just made your first PHP project in Visual Studio Code.
Your PHP exciting journey has just begun.
I hope that this will be useful to you and one day you become an excellent PHP programmer.
phpcs
Ioannis Kappas
vscode-phpcs
This linter plugin for Visual Studio Code provides an interface to phpcs. It will be used with files that have the “PHP” language mode.
Installation
Visual Studio Code must be installed in order to use this plugin. If Visual Studio Code is not installed, please follow the instructions here.
Linter Installation
Before using this plugin, you must ensure that phpcs is installed on your system. The preferred method is using composer for both system-wide and project-wide installations.
Once phpcs is installed, you can proceed to install the vscode-phpcs plugin if it is not yet installed.
NOTE: This plugin can detect whether your project has been set up to use phpcs via composer and use the project specific phpcs over the system-wide installation of phpcs automatically. This feature requires that both composer.json and composer.lock file exist in your workspace root or the phpcs.composerJsonPath in order to check for the composer dependency. If you wish to bypass this feature you can set the phpcs.executablePath configuration setting.
NOTE: You can also install phpcs on your system using pear or even manually but is beyond the scope of this plugin.
System-wide Installation
The phpcs linter can be installed globally using the Composer Dependency Manager for PHP.
Require phpcs package by typing the following in a terminal:
Project-wide Installation
The phpcs linter can be installed in your project using the Composer Dependency Manager for PHP.
Require phpcs package by typing the following at the root of your project in a terminal:
Plugin Installation
Basic Configuration
There are various options that can be configured to control how the plugin operates which can be set in your user, workspace or folder preferences.
phpcs.enable
[ Scope: All | Optional | Type: boolean | Default: true ]
This setting controls whether phpcs linting is enabled.
phpcs.executablePath
[ Scope: All | Optional | Type: string | Default: null ]
phpcs.standard
[ Scope: All | Optional | Type: string | Default: null ]
The following values are applicable:
You may set the default_standard used by phpcs using the following command:
or when using composer dependency manager from the root of your project issue the following command:
After you install the custom coding standard, you can make it available to phpcs by issuing the following command:
or when using composer dependency manager from the root of your project issue the following command:
The setting can be set to the absolute path to a custom coding standard:
or you can use the path to a custom ruleset:
The setting can be set to your workspace relative path to a custom coding standard:
or you can use the path to your project’s custom ruleset:
phpcs.autoConfigSearch
[ Scope: All | Optional | Type: boolean | Default: true ]
NOTE: This option does not apply for unsaved documents (in-memory).
phpcs.ignorePatterns
[ Scope: All | Optional | Type: array | Default: [] ]
An array of glob patterns to skip files and folders that match when linting your documents.
phpcs.errorSeverity
[ Scope: All | Optional | Type: number | Default: 5 ]
The minimum severity an error must have to be displayed. You may specify an integer value.
phpcs.warningSeverity
[ Scope: All | Optional | Type: number | Default: 5 ]
The minimum severity a warning must have to be displayed. You may specify an integer value.
phpcs.showWarnings
[ Scope: All | Optional | Type: boolean | Default: true ]
Control whether warnings are displayed.
phpcs.showSources
[ Scope: All | Optional | Type: boolean | Default: false ]
Show sniff source codes in diagnostic messages.
phpcs.trace.server
[ Scope: User | Optional | Type: string | Default: off ]
Advanced Configuration
phpcs.composerJsonPath
[ Scope: All | Optional | Type: string | Default: composer.json ]
This setting allows you to override the path to your composer.json file when it does not reside at the workspace root. You may specify the absolute path or workspace relative path to the composer.json file.
Diagnosing common errors
The phpcs report contains invalid json
This error occurs when something goes wrong in phpcs execution such as PHP Notices, PHP Fatal Exceptions, Other Script Output, etc, most of which can be detected as follows:
NOTE: The ‘-q’ parameter is automatically passed on phpcs v.2.6.2 and above to suppress such errors. Please update phpcs to a version >=2.6.2.
Acknowledgements
The extension architecture is based off of the Language Server Node Example.
Additional inspiration comes from Atom Linter-phpcs.
Contributing and Licensing
The project is hosted on GitHub where you can report issues, fork the project and submit pull requests.
The project is available under MIT license, which allows modification and redistribution for both commercial and non-commercial purposes.
Denis Waleev
Полезные расширения VS Code для работы с PHP
В этой статье хочу рассмотреть расширения для Visual Studio Code, которыми пользуюсь при разработке на PHP.
Набор основан на личном опыте. Возможно, я упустил какие-то другие хорошие расширения. Буду рад, если вы мне сообщите о них.
Здесь будут приведены только общие расширения для PHP в целом. Никаких специфичных для фреймворков.
Давайте перейдем непосредственно к списку.
PHP Intelephense
По умолчанию, VS Code предлагает очень общие подсказки, которые не всегда помогают при разработке на PHP. Улучшить эту ситуацию может расширение PHP Intelephense. С ним писать код станет значительно комфортней.
PHP DocBlocker
Очень удобно одной командой отформатировать php-файл. Не сказал бы, что часто может понадобиться, но такие случаи бывают.
PHP Debug
Мощное расширение для дебаггинга, которое добавляет поддержку XDebug. Придется потратить время на то, чтобы настроить данное расширение, но оно того стоит. Также есть возможность делать дебаггинг на удаленном сервере (честно еще не пользовался).
Заключение
Безусловно, расширений для PHP еще очень много, но я привел только тот минимум, которым я пользуюсь сейчас. Я пробовал и другие, но по разным причинам от них отказался. Да и сильно перегружать VS Code расширениями не хочется, ведь кроме этих, у меня есть расширения для фреймворков, HTML, CSS, JS, Git и т.д.
На этом все, пишите какие расширения для PHP используете вы.
PHP TDD
Jason Terando
PHP TDD Visual Studio Code Extension
This is a Visual Studio Code extension to assist with TDD in PHP. It includes tools that help to create, run and edit unit tests in your PHP application. By default, this extension uses PHPUnit, but it can be configured to run other unit test frameworks.
Features
Requirements
Note: As of version 0.1.0, if your PHP does not have JSON and tokenization built into it (i.e. they get loaded as extensions), they will get properly loaded if the enablePHPExtensions configuration property is set to true.
Operation
Initialize
Make sure you have PHP and Composer installed, and that you can run php and composer from a command prompt / shell. If not, use the links in the Requirements section to install.
To initialize the php-tdd, open a Workspace and run the command «PHP TDD: Initialize PHP Unit Test Project», which will do the following (by default configuration). The extension will copy files required for unit tests to the workspace folder. It will then ensure that Composer and PHPUnit are installed in the vendor folder.
Run or Edit a Single Unit Test
Once php-tdd is initialized, you can open a PHP file and move your cursor to a function or class (outside of a function) and run the command «PHP TDD: Run PHP Unit Test». If there is a unit test defined as a «@testFunction» comment line, it will be run, and the results shown in the status line (pass or fail). If there is not a unit test defined, a unit test will be created and brought up to edit. You can later edit the unit test by moving your cursor to the function or class, and run the command «PHP TDD: Edit PHP Unit Test».
All PHP-TDD Commands
About the Base Unit Test Case
The base unit test case implements the following three reflection-based methods to make unit testing a little more convenient.
This is provided as a convenience so that you can test any function as you are working on it. If you are categorically opposed to unit testing protected/private functions, don’t use it 🙂
Configuration
Extension Settings
This extension contributes the following settings:
Configuration Variables
The following configuration variables can be inserted into commaands and directory
Docker
If you want to run PHPUnit and Composer from Docker containers, php-tdd includes a Docker harness. You will need to override the following configuration settings in your workspace:
Release Notes
See (./CHANGELOG.md)[CHANGELOG.md] for release information.
To-Do’s
Development
Unit tests can be run by executing npm run unit-test or by loading the project in Visual Code and launch the «Unit Tests» tasks. Note that unit tests are run without launcing Visual Code. If you want to run the tests with Visual Code running, launch the «Integration Tests» task.
brapifra/vscode-phpserver
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Host / serve current workspace (or subfolder) with PHP.
There are multiple ways of running PHP server :
To stop the server, the PHP Server: Stop project command can be executed likewise.
All commands can be executed by pressing CTRL + SHIFT + P and typing the name of the command.
🥅 VS Code как IDE для PHP
Visual Studio Code при помощи встроенных возможностей, сторонних расширений и библиотек PHP можно превратить в полноценную IDE для разработки на PHP.
Написание кода
Есть настройки, но пользоваться можно сразу после установки.
Расширение PHP Namespace Resolver используется для удобного импорта namespace (причем с сортировкой) и создания новых пространств имен из файлов. Настроек не много. Мелочь, но +5 к удобству.
Расширение PHP DocBlocker предоставляет функционал для удобного и автоматического комментирования DocBlock.
Расширение phpcs предоставляет возможность оформлять код в соответсвии с выбранным стандартом. Неверно составленный код будет подсвечиваться.
Для настройки phpcs нужно установить расширение для VS Code (по ссылке выше) и пакет php_codesniffer для Composer:
Статический анализ
В минимальном варианте достаточно установить пакет phpstan/phpstan через Composer:
И через терминал можно запускать так (ссылка на документацию):
А для отображения результатов работы статического анализатора phpstan в интерфейсе VS Code, нужно установить расширение phpstan, создать конфиг phpstan.neon (ссылка):
Отладка
Расширение PHP Debug в совокупности с модулем PHP xdebug позволяют производить отладку PHP кода. Можно построчно выполнить файл, просмотреть стек вызовов и значения переменных. При этом запускать можно как отдельный файл, так и целый сайт о_О.
Установим модуль xdebug :
Теперь открываем файл /etc/php/VERSION/mods-available/xdebug.ini :
Вообще-то расширение PHP Debug по умолчанию предусматривает еще один конфиг Launch Built-in web server для запуска встроенного веб-сервера, но в моем случае это не нужно, так как использую локальный LAMP, а теперь вообще все в Docker и такая отладка в Docker.
Тестирование
Расширения для минимизации действий по запуску тестиров кода показались мне избыточны, потому что Visual Studio Code предоставляет функционал custom tasks, при помощи которого можно все это организовать.
Такими не сложными действиями мы превратили редактор кода Visual Studio Code в полноценную IDE для разработки проектов на PHP. Не все инструменты рассмотрены полностью, некоторые лишь очень поверхностно, но дальнейшую тонкую настройку оставляю в качестве домашнего задания 🙂
Best Visual Studio Code PHP Extensions for 2018
Microsoft’s Visual Studio Code is utterly competent with the PHP language. It’s something that shocked me personally when it was released as I didn’t expect it to come prepared for PHP developers. But yep, it is a strong development environment for PHP, and of course, there are plenty of extensions to be used with it.
In this article, I will go through the best available extensions that can be installed with your version of VSCode. With this list of essential extensions, you can configure your Visual Studio Code IDE into a wizardry-code-environment.
1. PHP Intellisense
First and foremost is Intellisense, I don’t think I could live without this one. Intellisense will offer to autocomplete on native PHP functions while you type. This extension by Felix Becker is super-responsive too, meaning unlike some other IDE’s, it always instantly gives you options within your autocomplete drop down.
2. PHP Debug
Although VSCode comes with a Debug widget fresh out the box, it doesn’t necessarily mean it works with all programming languages instantly. PHP is no exception, and you must download the framework for debugging to work with Visual Studio Codes debug module.
I wrote an article on how to set up debugging PHP with VS Code a while back. The tutorial instructs how to configure for code-level-simulation debugging and live-browser debugging. This is another feature that I couldn’t live without, and I’m almost sure that it’s the same for you!
3. DocBlocker
What on earth is DocBlocker I hear you ask, well, if you are asking that question, essentially a DocBlock is a comment block. See the following code snippet for example –
This extension makes it very quick to append this block to your code, wherever you may need it. What’s also great is that it comes packed with comment tags like @author, @method, @group and @return. You can quickly get access to these tags with their respective snippets by pressing the @ symbol and choosing from the drop-down list. Here is another example of the DocBlocker with some tags.
So, if you’re a big fan of comments, this way of commenting code is well worth putting in to practice. It’s not only helpful, but the style is known industry-wide.
4. phpfmt – PHP formatter
Because us coders love to type super-turbo-fingered-fast, we can’t always guarantee that our code layout is correctly tabbed and indented. With the above extension, you don’t have to worry, with a quick tap of CTRL + ALT + F, the extension will magically format the PHP into a pretty formatted file. You can also configure the extension to run its formatting every time you save the file too.
A quick note with this extension though, is that you must have the path to the PHP engine specified to work properly. Whether that be on a server on your local machine, it must be specified in the VSCode extension settings.
5. PHP Getter & Setter
Another convenient extension is the Getter & Setter package, I’ll give you half a millisecond to work out what it does. Yep, you guessed it, this extension quickly adds ‘get and set’ functions to your code. It’s as simple as right-clicking on the variable you want getters and setters for and executing the extensions helper. This extension will turbo-charge your object-oriented PHP development.
See the following code for an example of what it adds to your file for you.
6. Custom Snippet Pack
Just in-case your not aware of what snippets are, they mainly are keywords that you type out and hit return to print out a particular snippet of code to your file. For example, in this snippet pack, if we type ‘c’ and hit return, a full PHP class will be written to your file in an instant. These of course are extremely handy and help speed up development. The above pack has all super-globals and a few class-based snippets too.
7. PHP Storm Snippet Pack
If you’ve used PHP Storm before, you’ll already know about these handy snippets, if not, no worries, you know about them now! This pack has shortcuts for loops like, foreach require and include commands and more class-based snippets. Visit the link above for a data-table showing each shortcut and their description.
8. Import Checker
When using PHP frameworks like Laravel, declaring classes to use at the top of the file becomes widely used. But, over-time, you’re bound to have a cluttered list of classes, and one of them won’t be of required use. This checker extension essentially ‘lints’ those classes that aren’t necessary to your file and highlights them for deletion. Essentially, it’s a cleaning tool for your code and a good one at that.
9. PHP Files Extension
When specifying interface names, the possibility of comma-separating is present, meaning that the code will be pre-filled with these defined names. It’s well worth checking out.
Summary
The listed extensions within this article will give any PHP developer the perfectly equipped IDE for hassle-free development. Visual Studio Code is pretty basic out of the box, but with a little bit of effort, can be precisely what you want it to be. These nine extensions are probably the most important, but there are plenty more where they came from. The VS market place loads with extensions that you can browse through all-day-long.
If you have experience with some other extensions, be sure to leave them in the comments for other developers to discover too!
PHP_CodeSniffer
Christopher Allford
VS Code PHP_CodeSniffer Extension
Integrates PHP_CodeSniffer into VS Code.
This extension uses the version of PHPCS defined by the phpCodeSniffer.executable setting. Through the use of custom reports we are able to generate diagnostics, code actions, and document formatting that fully utilizes VS Code’s available features.
Configuration
Until you configure it, this extension will not lint any files.
Standard ( phpCodeSniffer.standard )
This dropdown and accompanying text input allow you to define the standard or ruleset path to use. When set to Default we rely on PHPCS to decide on the standard based on its own configuration. When set to Custom we pass the content of phpCodeSniffer.standardCustom to PHPCS; allowing you to define a custom rulset name or use an XML file.
Executable ( phpCodeSniffer.executable )
This text input allows for setting a path to a PHPCS executable. If a relative path is given it will be based on the workspace root that the document resides in (untitled documents use the first root). You may also set the phpCodeSniffer.autoExecutable option if you’d like for the extension to automatically search for an executable. This works by looking for a
File and Folder Exclusions ( phpCodeSniffer.exclude )
This array of glob patterns allows you to exclude files and folders from linting. While the extension does respect any file rules in your coding standard, this option allows you to define additional rules.
phpcs
shevaua
vscode-phpcs
This linter plugin for Visual Studio Code provides an interface to phpcs. It will be used with files that have the “PHP” language mode.
Installation
Visual Studio Code must be installed in order to use this plugin. If Visual Studio Code is not installed, please follow the instructions here.
Linter Installation
Before using this plugin, you must ensure that phpcs is installed on your system. The preferred method is using composer for both system-wide and project-wide installations.
Once phpcs is installed, you can proceed to install the vscode-phpcs plugin if it is not yet installed.
NOTE: This plugin can detect whether your project has been set up to use phpcs via composer and use the project specific phpcs over the system-wide installation of phpcs automatically. This feature requires that both composer.json and composer.lock file exist in your workspace root or the phpcs.composerJsonPath in order to check for the composer dependency. If you wish to bypass this feature you can set the phpcs.executablePath configuration setting.
NOTE: You can also install phpcs on your system using pear or even manually but is beyond the scope of this plugin.
System-wide Installation
The phpcs linter can be installed globally using the Composer Dependency Manager for PHP.
Require phpcs package by typing the following in a terminal:
Project-wide Installation
The phpcs linter can be installed in your project using the Composer Dependency Manager for PHP.
Require phpcs package by typing the following at the root of your project in a terminal:
Plugin Installation
Basic Configuration
There are various options that can be configured to control how the plugin operates which can be set in your user, workspace or folder preferences.
phpcs.enable
[ Scope: All | Optional | Type: boolean | Default: true ]
This setting controls whether phpcs linting is enabled.
phpcs.executablePath
[ Scope: All | Optional | Type: string | Default: null ]
phpcs.standard
[ Scope: All | Optional | Type: string | Default: null ]
The following values are applicable:
You may set the default_standard used by phpcs using the following command:
or when using composer dependency manager from the root of your project issue the following command:
After you install the custom coding standard, you can make it available to phpcs by issuing the following command:
or when using composer dependency manager from the root of your project issue the following command:
The setting can be set to the absolute path to a custom coding standard:
or you can use the path to a custom ruleset:
The setting can be set to your workspace relative path to a custom coding standard:
or you can use the path to your project’s custom ruleset:
phpcs.autoConfigSearch
[ Scope: All | Optional | Type: boolean | Default: true ]
NOTE: This option does not apply for unsaved documents (in-memory).
phpcs.ignorePatterns
[ Scope: All | Optional | Type: array | Default: [] ]
An array of glob patterns to skip files and folders that match when linting your documents.
phpcs.ignoreSource
[ Scope: All | Optional | Type: array | Default: [] ]
An array of ignored sources. It could be file, gitfs or another file system of any extension
phpcs.errorSeverity
[ Scope: All | Optional | Type: number | Default: 5 ]
The minimum severity an error must have to be displayed. You may specify an integer value.
phpcs.warningSeverity
[ Scope: All | Optional | Type: number | Default: 5 ]
The minimum severity a warning must have to be displayed. You may specify an integer value.
phpcs.showWarnings
[ Scope: All | Optional | Type: boolean | Default: true ]
Control whether warnings are displayed.
phpcs.showSources
[ Scope: All | Optional | Type: boolean | Default: false ]
Show sniff source codes in diagnostic messages.
phpcs.trace.server
[ Scope: User | Optional | Type: string | Default: off ]
Advanced Configuration
phpcs.composerJsonPath
[ Scope: All | Optional | Type: string | Default: composer.json ]
This setting allows you to override the path to your composer.json file when it does not reside at the workspace root. You may specify the absolute path or workspace relative path to the composer.json file.
phpcs.lintOnOpen
[ Scope: All | Optional | Type: boolean | Default: true ]
Lint file when open it
phpcs.lintOnSave
[ Scope: All | Optional | Type: boolean | Default: true ]
Lint file when save it
phpcs.lintOnType
[ Scope: All | Optional | Type: boolean | Default: true ]
Lint on every document change. Watch out! Work with big php file may cause high CPU usage.
phpcs.queueBuffer
[ Scope: All | Optional | Type: number | Default: 10 ]
The number of files in the queue for linting. When document is linting and it has any changes, the document will be queued up or replaced in queue.
phpcs.lintOnlyOpened
[ Scope: All | Optional | Type: boolean | Default: true ]
Lint only opened files within vscode. For better performance.
Diagnosing common errors
The phpcs report contains invalid json
This error occurs when something goes wrong in phpcs execution such as PHP Notices, PHP Fatal Exceptions, Other Script Output, etc, most of which can be detected as follows:
NOTE: The ‘-q’ parameter is automatically passed on phpcs v.2.6.2 and above to suppress such errors. Please update phpcs to a version >=2.6.2.
Acknowledgements
The extension architecture is based off of the Language Server Node Example.
Additional inspiration comes from Atom Linter-phpcs.
Contributing and Licensing
The project is hosted on GitHub where you can report issues, fork the project and submit pull requests.
The project is available under MIT license, which allows modification and redistribution for both commercial and non-commercial purposes.
kokororin
phpfmt for Visual Studio Code
The missing phpfmt extension for Visual Studio Code.
Installation
or keyboard shortcut Ctrl + Shift + I which is Visual Studio Code default formatter shortcut
or right mouse context menu Format Document or Format Selection
Format On Save
Respects editor.formatOnSave setting.
You can turn off format-on-save on a per-language basis by scoping the setting:
It is recommended to add the directory of the php.exe to the PATH environment variable on Windows. If it still not working, refer to #1 and Stack Overflow Related.
Configuration
Supported Transformations
PHP Sniffer & Beautifier
Samuel Hilson
PHP Sniffer & Beautifier for VS Code
This linter plugin for Visual Studio Code provides an interface to phpcs & phpcbf. It will be used with files that have the “PHP” language mode. This extension is designed to use auto configuration search mechanism to apply rulesets to files within a workspace. This is useful for developers who work with many different projects that have different coding standards.
Installation
Visual Studio Code must be installed in order to use this plugin. If Visual Studio Code is not installed, please follow the instructions here.
Usage
or keyboard shortcut alt+shift+f vs code default formatter shortcut
Format on save
Multi-Root Workspace Support
This extension now fully supports Multi-Root Workspaces. The extension previously used the first root folder in your workspace to configure and run both phpcs and phpcbf. The new system allows each workspace to be configured and run independently with respect to the root folder of the open file being sniffed. This means you can have phpcs functionality in one folder and have it disabled in another within a workspace.
Linter Installation
Before using this plugin, you must ensure that phpcs is installed on your system. The preferred method is using composer for both system-wide and project-wide installations.
Once phpcs is installed, you can proceed to install the vscode-phpsab plugin if it is not yet installed.
NOTE: This plugin can detect whether your project has been set up to use phpcbf via composer and use the project specific phpcs & phpcbf over the system-wide installation of phpcs & phpcbf automatically. This feature requires that both composer.json and composer.lock file exist in your workspace root or the phpsab.composerJsonPath in order to check for the composer dependency. If you wish to bypass this feature you can set the phpsab.executablePathCS and phpsab.executablePathCBF configuration settings.
System-wide Installation
The phpcs linter can be installed globally using the Composer Dependency Manager for PHP.
Require phpcs package by typing the following in a terminal:
You must specifically add the phpcs and phpcbf that you want to used to the global PATH on your system for the extension to auto detect them or set the executablePath for phpcs and phpcbf manually.
Project-wide Installation
The phpcs linter can be installed in your project using the Composer Dependency Manager for PHP.
Require phpcs package by typing the following at the root of your project in a terminal:
Plugin Installation
Basic Configuration
There are various options that can be configured to control how the plugin operates which can be set in your user, workspace or folder preferences.
phpsab.fixerEnable
[ Scope: Resource | Optional | Type: boolean | Default: true ]
This setting controls whether phpcbf fixer is enabled.
phpsab.fixerArguments
[ Scope: Resource | Optional | Type: string[] | Default: [] ]
Passes additional arguments to phpcbf runner.
phpsab.snifferEnable
[ Scope: Resource | Optional | Type: boolean | Default: true ]
This setting controls whether phpcs sniffer is enabled.
phpsab.snifferArguments
[ Scope: Resource | Optional | Type: string[] | Default: [] ]
Passes additional arguments to phpcs runner.
phpsab.executablePathCS
[ Scope: Resource | Optional | Type: string | Default: null ]
NOTE for Windows users: If the linter is installed globally, you must set the path to make this plugin work (example below). After saving this setting, don’t forget to reload VSCode!
phpsab.executablePathCBF
[ Scope: Resource | Optional | Type: string | Default: null ]
NOTE for Windows users: If the linter is installed globally, you must set the path to make this plugin work (example below). After saving this setting, don’t forget to reload VSCode!
phpsab.standard
[ Scope: Resource | Optional | Type: string | Default: null ]
The following values are applicable:
You may set the default_standard used by phpcbf using the following command:
or when using composer dependency manager from the root of your project issue the following command:
After you install the custom coding standard, you can make it available to phpcbf by issuing the following command:
or when using composer dependency manager from the root of your project issue the following command:
The setting can be set to the absolute path to a custom coding standard:
or you can use the path to a custom ruleset:
The setting can be set to your workspace relative path to a custom coding standard:
or you can use the path to your project’s custom ruleset:
phpsab.autoRulesetSearch
[ Scope: Resource | Optional | Type: boolean | Default: true ]
NOTE: This option does not apply for unsaved documents (in-memory). Also, the name of files that are searched for is configurable in this extension.
phpsab.allowedAutoRulesets
[ Scope: Resource | Optional | Type: array | Default: [] ]
An array of filenames that could contain a valid phpcs ruleset.
phpsab.snifferMode
[ Scope: All | Optional | Type: string | Default: onSave ]
onSave : The Sniffer will only update diagnostics when the document is saved.
onType : The Sniffer will update diagnostics as you type in a document.
phpsab.snifferTypeDelay
[ Scope: All | Optional | Type: number | Default: 250 ]
When snifferMode is onType this setting controls how long to wait after typing stops to update. The number represents milliseconds.
phpsab.snifferShowSources
[ Scope: All | Optional | Type: boolean | Default: false ]
Determines if the Sniffer includes the source of the diagnostic data with error messages.
Advanced Configuration
phpsab.composerJsonPath
[ Scope: Resource | Optional | Type: string | Default: composer.json ]
This setting allows you to override the path to your composer.json file when it does not reside at the workspace root. You may specify the absolute path or workspace relative path to the composer.json file.
Diagnosing common errors
phpsab.debug
[ Scope: All | Optional | Type: boolean | Default: false ]
Write debug information to the PHP Sniffer & Beautifier output channel and enable the display extra notices.
The phpcs report contains invalid json
This error occurs when something goes wrong in phpcs execution such as PHP Notices, PHP Fatal Exceptions, Other Script Output, etc, most of which can be detected as follows:
Acknowledgements
This extension is based off of the phpcs extension created by Ioannis Kappas, the PHP Sniffer extension create by wongjn and the existing phpcbf extension by Per Søderlind. It uses some portions of these extensions to provide the phpcs & phpcbf functionality with auto config search.
Contributing and Licensing
The project is hosted on GitHub where you can report issues, fork the project and submit pull requests. See the development guide for details.
The project is available under MIT license, which allows modification and redistribution for both commercial and non-commercial purposes.
How to use PHP with Visual Studio
First let me say I’ve never used PHP but I’m looking to learn it, so my question is this how do you use PHP within Visual Studio Ultimate? is it similar to how you declare JQuery i.e
I’ve done multiple searches on Google, but I don’t get the answer I’m looking for.
Or do I need a complete different bit of software to use it?
6 Answers 6
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
By default VS is not made to run PHP, but you can do it with extensions:
You can install an add-on with the extension manager, PHP Tools for Visual Studio.
If you want to install it inside VS, go to Tools > Extension Manager > Online Gallery > Search for PHP where you will find PHP Tools (the link above) for Visual Studio. Also you have VS.Php for Visual Studio. Both are not free.
You have also a cool PHP compiler called Phalanger:
If I’m not mistaken, the code you wrote above is JavaScript (jQuery) and not PHP.
If you want cool standalone IDE’s for PHP: (Free)
Composer
Ioannis Kappas
vscode-composer
This Visual Studio Code plugin provides an interface to Composer dependency manager for PHP. It also provides schema validation for composer.json configuration files.
Installation
You must install Visual Studio Code and Composer on your system before you can use this plugin.
Visual Studio Code Installation
If Visual Studio Code is not installed, please follow the instructions here.
Composer Installation
If Composer is not installed, please follow the instructions here.
Plugin Installation
Configuration
You can configure the following options by making changes to your user or workspace preferences.
composer.enabled
[ Scope: Global | Optional | Default: true ]
Use this setting to enable or disable this plugin.
composer.executablePath
[ Scope: Global | Required ]
Use this setting to specify the absolute path to the composer executable on your system.
Example user settings.json on Mac/Linux:
Example user settings.json on Windows:
Important: You will be unable to use this plugin unless you configure this setting before first use.
composer.ignorePlatformReqs
[ Scope: Global | Optional | Default: false ]
Use this setting to ignore all platform requirements (php, hhvm, lib-* and ext-*) and force the installation even if the local machine does not fulfill these.
composer.runInTerminal
[ Scope: Global | Optional | Default: true ]
Use this setting to defines whether the command is run in a terminal window or whether the output form the command is shown in the Output window. The default is to show the output in the terminal.
composer.runQuiet
[ Scope: Global | Optional | Default: false ]
composer.workingPath
[ Scope: Workspace | Optional | Default: null ]
Use this setting to specify the absolute or workspace relative path to your composer.json. If not specified the workspace root path is used as default.
Example user settings.json on Mac/Linux:
Example user settings.json on Windows:
Usage
Supported Commands
Composer: About
Display short information about composer.
Composer: Archive
Create an archive of this composer package.
Composer: Clear Cache
Clears composer’s internal package cache.
Composer: Depends
Displays detailed information about where a package is referenced.
Composer: Diagnose
Diagnoses the system to identify common errors.
Composer: Dump Autoloader
Dumps the autoloader.
Composer: Fund
Discover how to help fund the maintenance of your dependencies.
Composer: Init
The init command creates a basic composer.json file in the current directory.
Composer: Install
Installs the project dependencies from the composer.lock file if present, or falls back on the composer.json.
Composer: Licenses
Shows information about licenses of dependencies.
Composer: Outdated
Shows a list of installed packages that have updates available, including their current and latest versions.
Composer: Prohibits
Displays detailed information about why a package cannot be installed.
Composer: Remove
Removes a package from the require or require-dev.
Composer: Require
Adds required packages to your composer.json and installs them.
Composer: Run Script
Run the scripts defined in composer.json.
Composer: Self Update
Updates composer.phar to the latest version.
Composer: Show
Show information about packages.
Composer: Status
Show a list of locally modified packages.
Composer: Suggests
Show a sorted list of suggested packages.
Composer: Update
Updates your dependencies to the latest version according to composer.json, and updates the composer.lock file.
Composer: Validate
Validates a composer.json and composer.lock
Composer: Version
Shows the composer version.
Composer: Why
Displays detailed information about where a package is referenced.
Composer: Why Not
Displays detailed information about why a package cannot be installed.
Contributing and Licensing
The project is hosted on GitHub where you can report issues, fork the project and submit pull requests.
The project is available under MIT license, which allows modification and redistribution for both commercial and non-commercial purposes.
how to change the version of php in vscode?
I’m using iis and vscode to do php work. I recently updated iis from php7.3 to php7.4. My problem is that vscode is still using php7.3. I googled how to change the version in vscode and almost all the resources say that there’s a JSON file that can changed under php settings in File > preferences > settings. When I search for php I’m not seeing any of these options. What am I doing wrong?
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
You can set the value directly as seen in your screenshot. Entry is named PHP Version. If you do so for that particular workspace, a file will be created at
If you did set the PHP version on the page in your screenshot for that particular workspace then you should find in settings.json an entry that looks like the following
If you want to change the setting globally for all of your projects you can do the the following:
Open Explorer, or command line (cmd.exe) and type or copy the following line
Usually this will start vscode if not already running and open settings.json.
In that file at the beginning add after the opening bracket
Before you change these files manually, it might be a good idea to make a backup of these files.
ikappas/vscode-phpcs
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Looking for additional maintainers
Due to current work obligations, I am unable to commit enough time to steadily maintain this project, so I am looking for co-maintainers that are familiar with node.js, typescript and vscode plugin authoring.
If you want to help maintain this project, please contact me.
Setup Development Version
Run/Debug Development Version
To run the development version of the phpcs extension:
If you don’t have an open php file on your Extension Development Host the server debug session will timeout and you will need to relaunch it from the debug panel.
kolei/vsc_xdebug
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Настройка удаленной отладки PHP (XDebug) на Visual Studio Code (VSC)
Процесс первоначальной настройки локального (XAMPP) XDebug на VSC пропущен, такие мануалы есть в сети. Мне понадобилось к уже настроенному и рабочему VSC подключить отладку удаленного сайта.
Итак, дано: на локале винда с установленным VSC и удаленный Ubuntu-сервер (нулевый на виртуальной машине).
Настройка сервера (у меня Ubuntu 18.04)
До установки xdebug, нам сперва необходимо поставить некоторые другие пакеты. Установим пакет php-dev, который позволит нам компилировать динамические расширения для PHP. Как раз таким расширением является xdebug.
apt-get install php-dev
Теперь установим PEAR, который также включает PECL. Согласно их вебсайту, PECL — это репозиторий для расширений PHP, который предоставляет каталог всех известных расширений, а также услуги хостинга для скачивания и разработки PHP-расширений. Xdebug является одним из таких расширений.
apt-get install php-pear
Теперь мы можем установить/скомпилировать xdebug, используя PECL. Выполним следующую команду:
pecl install Xdebug
После успешной установки, в конце выдаст примерно следующее, запомните путь куда установлено расширение, нам он потом понадобится:
Добавим следующий код в конец php.ini:
Главное тут «pathMappings» : мы должны указать VSC какой локальный каталог соответствует удаленному.
About
Настройка удаленной отладки PHP на Visual Studio Code (XDebug)
Как запустить или отладить php в Visual Studio Code (VSCode)
Я не могу найти способ запуска или отладки php на Visual studio code, кто-нибудь знает как?
Отладка PHP с VSCode с помощью расширения vscode-php-debug
VSCode теперь может поддерживать отладку проектов PHP с помощью расширения vscode-php-debug.
Это расширение использует XDebug в фоновом режиме и позволяет использовать точки останова, часы, трассировку стека и тому подобное:
Насколько я читал о нем сегодня, на данный момент вы не можете отлаживать ничего, кроме node.js, JavaScript и TypeScript, но они сказали, что хотят добавить новые языки, которые вы сможете отлаживать. Редактор все еще находится в разработке. Тем не менее, я не думаю, что в будущем появится отладчик php, поскольку php находится на стороне сервера, поэтому вы не можете отлаживать его только на вашем клиенте.
Если вы хотите отлаживать php, я могу порекомендовать xDebug.
Updated:
Теперь возможна отладка с помощью VS-кода. Для этого необходимо установить расширение XDebug и php-debug для VScode.
Согласно ссылке, шаги следующие:
Обратите внимание, что в статье по ссылке есть конкретные детали, включая значения PHP для конфигурации пользователя VS Code и так далее.
Это’ы на самом деле можно получить запуска PHP без xdebug и без установки дополнительных расширений.
Если вы просто хотите, чтобы исполняемый файл php оценивать PHP-код и показать вывод в терминал (т. е. не в браузере), то вам просто необходимо скопировать следующие настройки в настройках пользователя:
С другой стороны, если вы хотите запустить PHP с помощью веб-сервера с браузером, вы должны установить это путем создания задача построения. Для того чтобы создать задачу, вы должны работать на папку с рабочей области. Если у вас есть рабочую область, откройте папку, перейдите к задачи > настроить задачи. `, затем нажмите Enter, а затем выберите в «другом» вариант. Делаю это создаст задачи.JSON-файл в папке рабочей области.
Теперь скопируйте Мои настройки ниже в ваших задач.JSON-файл:
Теперь, если у вас есть php-файл из рабочей области, можно нажать сочетание клавиш Ctrl+Шифт+в (⌘+Шифт+B в macOS), а также двух вышеупомянутых задач должно показать. Выберите пуск сервера для работы с PHP’встроенный сервер, потом запустить в браузере, чтобы запустить в данный момент открыт файл из браузера (это предполагает, что ваш корневой рабочем пространстве также корень документа). Обратите внимание, что если у вас уже есть веб-сервер работает, вы можете удалить задачу запуска сервера и обновление локальным localhost:8080 части, чтобы указать любой URL, который вы используете.
PHP in Visual Studio Code: Setup Debugging
Table of Contents
This tutorial with show you how to setup debugging PHP in Visual Studio Code as the code editor.
PHP executable not found error
In the beginning I will also show you how to fix the Visual Studio Code “PHP executable not found” error!
To fix it, you will need to find the PHP folder. Since I am using XAMPP, the path is as follows:
Then, we go to the “Edit the system environment variables” in Windows 10.
Click the “Environment Variables…” button, to open the dialog box.
Then, go to the “Path” line and double click it!
Next, we need to add a new line in the shown dialog box. In the new added line, we paste the PHP path we copied before!
Hit “OK” and close all the dialog boxes and then reopen Visual Studio Code and the error should not show again!
Setup PHP Debugging
First of all, we need to make sure that our XAMPP Apache server is running.
We start the Apache server from the XAMPP control form. Open it and hit the “Start” button in the Apache line of modules.
Open a browser of your choice, and type localhost in the url field. The Apache dashboard should appear. If you don’t see that page, then something is wrong with your XAMPP or Apache server.
If the dashboard is working, then go to the PHPinfo page.
The PHPinfo page gives you all the required information about the PHP engine running on your server.
We will be using the XDEBUG extension for PHP to setup debugging.
You can get this extension in this path: https://xdebug.org/wizard
Next, we need to copy everything from the PHPinfo page and paste it in the input filed provided by the xdebug.org/wizard link.
Then, we click the “Analyse my phpinfo() output” button, which then generates our XDebug download file, which will work with our PHP installation.
And we are done with that part.
Setup Visual Studio Code
In Visual Studio Code, we go to the Extension section and search for “PHP Debug” extension.
Install the extension!
After installation, you need to scroll down in the details section and copy the below lines:
The lines above enable remote debugging.
Next, we find the php.ini (the PHP configuration file).
Open the file and scroll down, somewhere by the end of the file and paste the above xdebug lines that you have copied.
There is also, one more line to be paste in the php.ini file.
If you go back to the browser and the xdebug.org/wizard.php page, you need to copy zend_extension line.
Mine is as follows, but depending on your PHP configuration generated by your phpinfo() page, you might get different results:
We paste the above line, below the previous 3 lines in the php.ini file.
The final 4 lines will be:
Now, we are all set.
Each time, you update the php.ini file, you need to restart the Apache Server.
We do that from the XAMPP control panel, by hitting the Stop/Start button in the panel.
Debugging in action
To see debugging in action we need to add a breakpoint in the line of the code we want the debugging to start.
Then we go to the debug extension in Visual Studio Code and we hit the “Listen for XDebug” button, to enable the debugging.
To see debugging in action, we go to the browser and open the php page, we are working on currently.
When the page is opening, when it arrives to the breakpoint we have set before, it will stop running and in the Visual Studio Code we can manually move each PHP code line.
In the left panel in the Visual Studio Code you will see the “Variables” section, where you could watch the local variables, superglobals and/or user defined constants.
To move the code forward or perform any other action, you can use the panel as shown below.
In this way, you will be able to execute the code line by line and see if the code is behaving properly.
In my example I go through a for loop and monitor each executed line and the values we are getting, but you can use this method to debug any part of your PHP code.
Conclusion
The XDebug is not the only tool that allows PHP debugging, but I find it to be one of the best tools for that purpose.
It is always recommended to do debugging while you code in PHP, as you will be able to find any possible errors much quicker and easier and it will help you to produce bug-free PHP code.
This concludes the tutorial, hopefully this was useful to you!
Visual Studio Code
Материал из Joomla! Documentation
Visual Studio Code is a source code editor developed by Microsoft for Windows, Linux and macOS (including M1 Macs). It includes support for debugging, embedded Git control and GitHub, syntax highlighting, intelligent code completion, snippets, and code refactoring.
The main characteristic of the editor is that it is extensible and it has a huge collection of extensions maintained by users and by Microsoft itself. The Extensions for the Visual Studio family of products can be found here: https://marketplace.visualstudio.com/VSCode.
As a general introduction, this is a presentation about the topic Joomla Development with Visual Studio Code, by René Kreijveld, Joomla developer Destiny B.V. Joomla User Group London, 16th march 2021.
On this page, we detail a list of recommended extensions to configure VSCode to support PHP and Joomla.
This is a list of extensions to support PHP on VSCode:
The Git protocol is natively supported on VSCode. However, there are extensions to improve code and repository management. This is a list of featured extensions for this task:
This is a list of extensions to support Joomla on VSCode:
This is a list of extensions to support remote SSH development:
This is a list of handy extensions highly recommended to ease the development:
Содержание
PHP Debug Configuration [ править ]
The extension supports the most common configurations of PHP XDebug. It fully integrates all VSCode features to debug PHP scripts.
To configure the extension, visit the official documentation here: https://github.com/felixfbecker/vscode-php-debug#installation
As a sample configuration for VSCode debugging, this is a common launch.json:
Related to the launch.json configuration that felixfbecker/vscode-php-debug requires, it is the configuration of PHP XDebug itself.
At this time, your development environment could have xdebug-2 or xdebug-3. They differ in the required parameters. To configure PHP XDebug, these are the most common settings for php.ini.
XDebug 2 configuration [ править ]
XDebug 3 configuration [ править ]
To know more about how XDebug works internally to connect to the Editor, check the documentation here Xdebug 3 — Documentation.
phpcs Configuration [ править ]
The extension supports the most common configurations of PHP_CodeSniffer.
By default, PHP_CodeSniffer comes with several coding standards. Once the extension is installed, it works with PSR2.
To configure the extension to apply the Joomla! Coding Standards, install the rules following the official guide: https://developer.joomla.org/coding-standards/html.html
Once the Joomla! Coding Standards is installed, configure the User Settings following this sample configuration:
Configuration of PHP Intelephense [ править ]
To configure the extension, visit the official documentation here: https://github.com/bmewburn/vscode-intelephense#quick-start
The extension does not require additional configuration.
VSCode comes with basic support of the PHP language. So, it is probably a good idea to disable the default support to avoid conflicts:
As an alternative, it is also a very popular extension: PHP IntelliSense felixfbecker.php-intellisense Advanced Autocompletion and Refactoring support for PHP.
PHPUnit Configuration [ править ]
To configure the extension, visit the official documentation here: https://github.com/elonmallin/vscode-phpunit#setup
The extension integrates PHP Unit with VSCode, so all features of PHP Unit are integrated with VSCode and can also be parametrized for further integration with the user interface.
This is a sample configuration of the extension:
php cs fixer Configuration (Only for PSR2) [ править ]
To configure the extension, visit the official documentation here: https://github.com/junstyle/vscode-php-cs-fixer#installation
The extension integrates PHP-CS-Fixer with VSCode, so all features of PHP-CS-Fixer are integrated with VSCode and can also be parametrized for further integration with the user interface.
To automatically, apply PHP-CS-Fixer to PHP files, configure the user settings in this way:
PHP Phan (Analyzer) Configuration [ править ]
This is a sample configuration of the extension:
phpmd Configuration [ править ]
To configure the extension, visit the official documentation here: https://github.com/felixfbecker/vscode-php-debug#installation
The extension does not require additional configuration.
This is a sample configuration of the extension:
Configure EditorConfig for VS Code [ править ]
EditorConfig is a file format and collection of text editor plugins for maintaining consistent coding styles between different editors and IDEs.
Getting Started with PHP Tools
Welcome to PHP Tools for Visual Studio. The following guide will help you with the basics, so you can quickly start working with PHP in Microsoft Visual Studio.
Note: PHP Tools for Visual Studio is a Visual Studio extension. Please note, licensing of Visual Studio Express does not allow the extensibility. Thus PHP Tools does not support VS Express editions.
Getting to know the IDE
When you launch Visual Studio, you are welcomed with the Start Page. This allows you to open recent projects or create new ones quickly.
When a project is opened, you can see the files that are a part of the project in the Solution Explorer. The Solution Explorer allows you to manage, search and open files, their properties and the project properties.
The editor area contains opened files. It allows you to see and modify the content, and take advantage of advanced IntelliSense features, navigation features, syntax highlighting, live error detection and more.
First PHP project
Most of the features in Visual Studio work within the context of a project. Debugging, IntelliSense, testing or configuring web server depends on a PHP project. The project corresponds to a single application or a library, it can be bound to a source control or configured to publish modified files onto a remote server.
There are several ways to create a new project in Visual Studio by:
New PHP Project from Scratch
An empty PHP Project is the simplest way of getting started with PHP Tools. Go to ‘Menu | File | New | Project’ and look for ‘PHP’ group. Find the project template you need and confirm.
Additional files and directories can be added in various ways:
New Project in an Existing Folder
Importing Local Files to a Project
If you already have a project, you can add existing files. See New PHP project from scratch for more information.
Editing a PHP File
PHP Tools provides Visual Studio with a smart editor of PHP files.
Built-in code snippets help you to write code fast avoiding typos. You can insert a code snippet Ctrl+K,X like new function body, for loop, try/catch construct and more to speed up your development. Newly inserted snippet is automatically formatted and cursor position moved directly inside the new code so you can type your code instantly. Moreover selected area of a code can be surrounded by a snippet Ctrl+K,S to avoid the need of copy-pasting and other refactoring.
Run and Debug Your PHP Project
Configuring PHP
Running the application locally requires properly configured PHP. To enable support for debugging, PHP extension Xdebug has to be installed and configured as well.
PHP Tools help with the setup in two ways.
Once you start your first application F5 and there is no valid PHP installation found, you can download and setup a recommended version of PHP with pre-configured Xdebug within one click from Microsoft Web Platform Installer. This is the most recommended option for most users.
For users with custom requirements or requiring to use their existing PHP installation, PHP Tools help by checking the configuration and suggesting recommended fixes eventually.
Remote Debugging and Custom Web Server
To run the application on a remote server or locally using a not-listed Web Server, go to project properties. Select Custom Web Server and enter its URL.
In this case, PHP and Xdebug configurations are not checked whether they are installed or configured properly. You have to make sure that:
Test Your Application
PHP project integrates into Visual Studio Test Explorer. Go to Menu | Test | Windows | Test Explorer to manage the test cases. Project files are scanned and PHP Unit test cases are automatically listed within the Test Explorer window.
Within the window, you can start or debug your test cases using built-in PHP Unit framework.
Note: availability of the Test Explorer feature depends on your edition of Visual Studio.
Customization
The Visual Studio environment is fully customizable. Most common tasks you may want to customize are listed below.
File Extension Being Opened by PHP Editor
Fonts and Colors
Keyboard Mappings
PHP Editor Options
That’s It
Thank you for reading our quick start guide. There is much more you can do with Visual Studio and PHP Tools. For more tips and/or questions, please see the rest of the documentation and the product’s features page.
Отладка php в Visual Studio Code (Xdebug, Windows)
В некоторых случаях может возникнуть необходимость отладки приложений на php. Visual Studio code предоставляет такую возможность при условии установки дополнительного расширения PHP Debug (marketplace, github).
Установка PHP Debug
Установка и настройка Xdebug
PHP Debug использует для отладки Xdebug. Для настройки Xdebug пройдите по ссылке. Предполагается, что на локальной машине уже установлен и настроен сервер apache. Здесь и далее действия указаны для Windows. Можно создать файл, например, test.php содержащий:
Открыть его в браузере и скопировать содержимое страницы в диалоговое окно. Другой способ:
Кроме этого, добавьте нижеследующие строки. Итоговое добавление будет примерно таким:
Как вы уже, возможно догадались, в данном примере на локальной машине установлен XAMPP.
Примечание: С версией Xdebug 2.5 и выше Visual Studio code не работает. Поэтому выбирайте соответствующий вашей версии php файл *.dll.
Настройка Visual Studio code
Вызовите панель отладки (1) и нажмите на иконку с маленькой шестеренкой (2).
Настройка PHP Debug на этом окончена.
Отладка php в Visual Studio code
Откройте в браузере ваше приложение\сайт. Откройте папку с приложением в Visual Studio code. Установите в нужных файлах и строках точки остановки. Откройте панель отладки и выберите для запуска отладки команду Listen for Xdebug (1). Нажмите кнопку запуска (2).
Обновите страницу в браузере и наслаждайтесь.
The best setting.json for PHP development with Visual Studio Code
Overview
PHP is a dynamic object-oriented language that brings the developer the power of OOP along with the flexibility of dynamic typing. Type annotations are supported in PHP which allows you the ability to define the runtime type of function parameters.
IDE’s can be used to increase one’s productivity since most of them have built-in auto-completion and other useful features such as “Go to definition”, and “Find all references”.
One popular IDE is PHPStorm, but today we will highlight which Visual Studio Code extensions transform Visual Studio Code into a full-fledged IDE alternative for PHP.
With great power, comes great responsibility, and because Visual Studio Code is a powerful text editor that brings an extremely powerful extensibility API, it’s easy to find yourself with a nonsensical settings.json file. At the end of this post, your visual studio code will have these productivity features:
These features will be implemented by installing these extensions:
Step 1.
This will allow our extensions to be used to their fullest extent and prevent any functional collisions.
Step 2.
By default, the php-redis extension is not included in the default configuration. So that means you will not have auto-complete for the Redis class. Now, let’s configure optimal Intelephense settings. Quick tip, when you’re editing a setting.json file in vscode, you can see the default value for the configuration item by typing the colon character, : and then clicking the tooltip.
Step 3 PHP Code Sniffer settings
Step 4. PHPDoc Block settings
Step 5. Optional settings.
These settings are more of a more personal flavor, but I’ve shared them here because I believe they are amazing.
The last 2 are great because the editor will stay open when you’ve navigated to a file from a find all reference, or go to definition click.
Visual studio code php
Let’s next review the process of traversing your file system. Or, in other words, what is the fastest way to open a file, or a class, or a PHP method. It’s vital that we streamline this workflow as best as we can. «,»excerpt»:»Let’s next review the process of traversing your file system. Or, in other words, what is the. «,»source_code»:null,»keyConcepts»:null,»position»:3,»dateSegments»:<"published":"November 16, 2017","publishedAlt":"Nov 16th, 2017","publishedDiff":"4 years ago","whenAvailableForHumans":"4 years">,»length»:310,»lengthForHumans»:»5:10″,»isNew»:false,»isScheduled»:false,»path»:»\/episodes\/1196″,»taxonomy»:<"name":"Tooling","path":"https:\/\/laracasts.com\/browse\/tooling">,»series»:<"title":"Visual Studio Code for PHP Developers","taxonomy":<"name":"Tooling","path":"https:\/\/laracasts.com\/browse\/tooling">,»thumbnail»:»https:\/\/laracasts.nyc3.cdn.digitaloceanspaces.com\/series\/thumbnails\/visual-studio-code-for-php-developers.png»,»path»:»\/series\/visual-studio-code-for-php-developers»>,»viewingStatus»:<"scheduled":false,"watchable":true,"requiresReactivation":null,"requiresBillingDetails":false,"isCompleted":null>,»hasTranscript»:false,»vimeoId»:»243144512″>,<"id":1197,"className":"Laracasts\\Video","chapter":1,"type":"episode","title":"Vim Keybinding Goodness","body":"
The programming world splits into two groups: those who research Vim keybindings for each new editor they try, and those who are still figuring out how to exit Vim. If you’re among the former, let’s get these keybindings working. «,»excerpt»:»The programming world splits into two groups: those who research Vim keybindings for each new editor they. «,»source_code»:null,»keyConcepts»:null,»position»:4,»dateSegments»:<"published":"November 16, 2017","publishedAlt":"Nov 16th, 2017","publishedDiff":"4 years ago","whenAvailableForHumans":"4 years">,»length»:227,»lengthForHumans»:»3:47″,»isNew»:false,»isScheduled»:false,»path»:»\/episodes\/1197″,»taxonomy»:<"name":"Tooling","path":"https:\/\/laracasts.com\/browse\/tooling">,»series»:<"title":"Visual Studio Code for PHP Developers","taxonomy":<"name":"Tooling","path":"https:\/\/laracasts.com\/browse\/tooling">,»thumbnail»:»https:\/\/laracasts.nyc3.cdn.digitaloceanspaces.com\/series\/thumbnails\/visual-studio-code-for-php-developers.png»,»path»:»\/series\/visual-studio-code-for-php-developers»>,»viewingStatus»:<"scheduled":false,"watchable":true,"requiresReactivation":null,"requiresBillingDetails":false,"isCompleted":null>,»hasTranscript»:false,»vimeoId»:»243149996″>,<"id":1198,"className":"Laracasts\\Video","chapter":1,"type":"episode","title":"Dynamic Snippets","body":"
Please don’t manually type out your various class and method structures. These are perfect use-cases for custom snippets. Let’s create a few together, while reviewing some key variable names to make them more dynamic. «,»excerpt»:»Please don’t manually type out your various class and method structures. These are perfect use-cases for custom. «,»source_code»:null,»keyConcepts»:null,»position»:5,»dateSegments»:<"published":"November 16, 2017","publishedAlt":"Nov 16th, 2017","publishedDiff":"4 years ago","whenAvailableForHumans":"4 years">,»length»:369,»lengthForHumans»:»6:09″,»isNew»:false,»isScheduled»:false,»path»:»\/episodes\/1198″,»taxonomy»:<"name":"Tooling","path":"https:\/\/laracasts.com\/browse\/tooling">,»series»:<"title":"Visual Studio Code for PHP Developers","taxonomy":<"name":"Tooling","path":"https:\/\/laracasts.com\/browse\/tooling">,»thumbnail»:»https:\/\/laracasts.nyc3.cdn.digitaloceanspaces.com\/series\/thumbnails\/visual-studio-code-for-php-developers.png»,»path»:»\/series\/visual-studio-code-for-php-developers»>,»viewingStatus»:<"scheduled":false,"watchable":true,"requiresReactivation":null,"requiresBillingDetails":false,"isCompleted":null>,»hasTranscript»:false,»vimeoId»:»243154313″>,<"id":1199,"className":"Laracasts\\Video","chapter":1,"type":"episode","title":"The Glorious Built-in Terminal","body":"
If you’re accustomed to opening a separate Terminal or iTerm window each time you need to trigger a console command, if you wish, you may now accomplish this directly from Visual Studio Code, via its terminal panel. Ctrl-` is your friend. «,»excerpt»:»If you’re accustomed to opening a separate Terminal or iTerm window each time you need to trigger. «,»source_code»:null,»keyConcepts»:null,»position»:6,»dateSegments»:<"published":"November 16, 2017","publishedAlt":"Nov 16th, 2017","publishedDiff":"4 years ago","whenAvailableForHumans":"4 years">,»length»:95,»lengthForHumans»:»1:35″,»isNew»:false,»isScheduled»:false,»path»:»\/episodes\/1199″,»taxonomy»:<"name":"Tooling","path":"https:\/\/laracasts.com\/browse\/tooling">,»series»:<"title":"Visual Studio Code for PHP Developers","taxonomy":<"name":"Tooling","path":"https:\/\/laracasts.com\/browse\/tooling">,»thumbnail»:»https:\/\/laracasts.nyc3.cdn.digitaloceanspaces.com\/series\/thumbnails\/visual-studio-code-for-php-developers.png»,»path»:»\/series\/visual-studio-code-for-php-developers»>,»viewingStatus»:<"scheduled":false,"watchable":true,"requiresReactivation":null,"requiresBillingDetails":false,"isCompleted":null>,»hasTranscript»:false,»vimeoId»:»243155815″>,<"id":1200,"className":"Laracasts\\Video","chapter":1,"type":"episode","title":"Git Ready","body":"
For the Laravel users among you, the Artisan extension allows you to trigger any artisan command straight for the GUI. This means, within seconds, you can generate and load your new controller. «,»excerpt»:»For the Laravel users among you, the Artisan extension allows you to trigger any artisan command straight. «,»source_code»:null,»keyConcepts»:null,»position»:8,»dateSegments»:<"published":"November 16, 2017","publishedAlt":"Nov 16th, 2017","publishedDiff":"4 years ago","whenAvailableForHumans":"4 years">,»length»:94,»lengthForHumans»:»1:34″,»isNew»:false,»isScheduled»:false,»path»:»\/episodes\/1201″,»taxonomy»:<"name":"Tooling","path":"https:\/\/laracasts.com\/browse\/tooling">,»series»:<"title":"Visual Studio Code for PHP Developers","taxonomy":<"name":"Tooling","path":"https:\/\/laracasts.com\/browse\/tooling">,»thumbnail»:»https:\/\/laracasts.nyc3.cdn.digitaloceanspaces.com\/series\/thumbnails\/visual-studio-code-for-php-developers.png»,»path»:»\/series\/visual-studio-code-for-php-developers»>,»viewingStatus»:<"scheduled":false,"watchable":true,"requiresReactivation":null,"requiresBillingDetails":false,"isCompleted":null>,»hasTranscript»:false,»vimeoId»:»243173158″>,<"id":1202,"className":"Laracasts\\Video","chapter":1,"type":"episode","title":"PHP Automatic Imports","body":"
We’re getting nitpicky at this point, but that’s okay. Having to reach for the mouse to right-click on a symbol to perform any kind of contextual action is a bit annoying. Let’s instead assign a custom keyboard shortcut so that my hands can remain on the keyboard permanently. «,»excerpt»:»We’re getting nitpicky at this point, but that’s okay. Having to reach for the mouse to right-click. «,»source_code»:null,»keyConcepts»:null,»position»:12,»dateSegments»:<"published":"November 16, 2017","publishedAlt":"Nov 16th, 2017","publishedDiff":"4 years ago","whenAvailableForHumans":"4 years">,»length»:93,»lengthForHumans»:»1:33″,»isNew»:false,»isScheduled»:false,»path»:»\/episodes\/1205″,»taxonomy»:<"name":"Tooling","path":"https:\/\/laracasts.com\/browse\/tooling">,»series»:<"title":"Visual Studio Code for PHP Developers","taxonomy":<"name":"Tooling","path":"https:\/\/laracasts.com\/browse\/tooling">,»thumbnail»:»https:\/\/laracasts.nyc3.cdn.digitaloceanspaces.com\/series\/thumbnails\/visual-studio-code-for-php-developers.png»,»path»:»\/series\/visual-studio-code-for-php-developers»>,»viewingStatus»:<"scheduled":false,"watchable":true,"requiresReactivation":null,"requiresBillingDetails":false,"isCompleted":null>,»hasTranscript»:false,»vimeoId»:»243189100″>,<"id":1206,"className":"Laracasts\\Video","chapter":1,"type":"episode","title":"Sweet PHP Debugging in Four Minutes","body":"
The useful \»Import Cost\» extension allows us to automatically visualize the size of each JavaScript dependency we import. It does this by appending a small, non-intrusive label next to each import. Are you importing a massive dependency that you didn’t know about? Well, if you are, this extension will make it crystal clear.»,»excerpt»:»The useful \»Import Cost\» extension allows us to automatically visualize the size of each JavaScript dependency we. «,»source_code»:null,»keyConcepts»:null,»position»:16,»dateSegments»:<"published":"November 16, 2017","publishedAlt":"Nov 16th, 2017","publishedDiff":"4 years ago","whenAvailableForHumans":"4 years">,»length»:141,»lengthForHumans»:»2:21″,»isNew»:false,»isScheduled»:false,»path»:»\/episodes\/1209″,»taxonomy»:<"name":"Tooling","path":"https:\/\/laracasts.com\/browse\/tooling">,»series»:<"title":"Visual Studio Code for PHP Developers","taxonomy":<"name":"Tooling","path":"https:\/\/laracasts.com\/browse\/tooling">,»thumbnail»:»https:\/\/laracasts.nyc3.cdn.digitaloceanspaces.com\/series\/thumbnails\/visual-studio-code-for-php-developers.png»,»path»:»\/series\/visual-studio-code-for-php-developers»>,»viewingStatus»:<"scheduled":false,"watchable":true,"requiresReactivation":null,"requiresBillingDetails":false,"isCompleted":null>,»hasTranscript»:false,»vimeoId»:»243204522″>,<"id":1210,"className":"Laracasts\\Video","chapter":1,"type":"episode","title":"Pour Me a Glass of ESLint","body":"
Let’s supercharge our JavaScript (including Vue templates) error and style guide detection with ESLint. Once installed, you’ll stop and wonder how you were able to code effectively before this wonderful addition to your tool belt. «,»excerpt»:»Let’s supercharge our JavaScript (including Vue templates) error and style guide detection with ESLint. Once installed, you’ll. «,»source_code»:null,»keyConcepts»:null,»position»:17,»dateSegments»:<"published":"November 16, 2017","publishedAlt":"Nov 16th, 2017","publishedDiff":"4 years ago","whenAvailableForHumans":"4 years">,»length»:342,»lengthForHumans»:»5:42″,»isNew»:false,»isScheduled»:false,»path»:»\/episodes\/1210″,»taxonomy»:<"name":"Tooling","path":"https:\/\/laracasts.com\/browse\/tooling">,»series»:<"title":"Visual Studio Code for PHP Developers","taxonomy":<"name":"Tooling","path":"https:\/\/laracasts.com\/browse\/tooling">,»thumbnail»:»https:\/\/laracasts.nyc3.cdn.digitaloceanspaces.com\/series\/thumbnails\/visual-studio-code-for-php-developers.png»,»path»:»\/series\/visual-studio-code-for-php-developers»>,»viewingStatus»:<"scheduled":false,"watchable":true,"requiresReactivation":null,"requiresBillingDetails":false,"isCompleted":null>,»hasTranscript»:false,»vimeoId»:»243226893″>,<"id":1215,"className":"Laracasts\\Video","chapter":1,"type":"episode","title":"Type Checking JavaScript Files","body":"
We’re getting nitpicky at this point, but that’s okay. Having to reach for the mouse to right-click on a symbol to perform any kind of contextual action is a bit annoying. Let’s instead assign a custom keyboard shortcut so that my hands can remain on the keyboard permanently. «,»excerpt»:»We’re getting nitpicky at this point, but that’s okay. Having to reach for the mouse to right-click. «,»source_code»:null,»keyConcepts»:null,»position»:12,»dateSegments»:<"published":"November 16, 2017","publishedAlt":"Nov 16th, 2017","publishedDiff":"4 years ago","whenAvailableForHumans":"4 years">,»length»:93,»lengthForHumans»:»1:33″,»isNew»:false,»isScheduled»:false,»path»:»\/episodes\/1205″,»taxonomy»:<"name":"Tooling","path":"https:\/\/laracasts.com\/browse\/tooling">,»series»:<"title":"Visual Studio Code for PHP Developers","taxonomy":<"name":"Tooling","path":"https:\/\/laracasts.com\/browse\/tooling">,»thumbnail»:»https:\/\/laracasts.nyc3.cdn.digitaloceanspaces.com\/series\/thumbnails\/visual-studio-code-for-php-developers.png»,»path»:»\/series\/visual-studio-code-for-php-developers»>,»viewingStatus»:<"scheduled":false,"watchable":true,"requiresReactivation":null,"requiresBillingDetails":false,"isCompleted":null>,»hasTranscript»:false,»vimeoId»:»243189100″>>,»progress»:<"lastEpisodePositionCompleted":null>,»lesson»:<"id":1204,"className":"Laracasts\\Video","chapter":1,"type":"episode","title":"Magical PHP Formatting With Automatic Fixes","body":"
You may also need to specify the php-cs-fixer executable path in your settings.json file, like I did. \n
For example, if you install php-cs-fixer globally with Composer via composer global require friendsofphp\/php-cs-fixer then you should add something like this line in your settings.json :\n «php-cs-fixer.executablePath»: «\/home\/[YOU_USER_NAME]\/.config\/composer\/vendor\/bin\/php-cs-fixer», \n
This also assumes that you have already added your global Composer directory to your PATH. \n
.php_cs fix not working. \n
Mostly windows users facing this problem. The problem is in «.php-cs» file array have «self_accessor» code it’s producing some kind of error. for me, I remove it and it’s work. \n
https: \/\/gist.github.com\/creativeboyab\/39ade2c021610edbe8ea1005457402c4 \n»,»strippedBody»:».php_cs fix not working.\nMostly windows users facing this problem. The problem is in «.php-cs» file array have «self_accessor» code it’s producing some kind of error. for me, I remove it and it’s work.\nhttps: \/\/gist.github.com\/creativeboyab\/39ade2c021610edbe8ea1005457402c4\n»,»bodyInMarkdown»:».php_cs fix not working.\n\nMostly windows users facing this problem. The problem is in \».php-cs\» file array have \»self_accessor\» code it’s producing some kind of error. for me, I remove it and it’s work.\n\nhttps: \/\/gist.github.com\/creativeboyab\/39ade2c021610edbe8ea1005457402c4″,»path»:»\/comments\/1573″,»relativePublishDate»:»2 years ago»,»edited»:false,»user»:<"id":145444,"username":"mdab","avatar":"\/\/www.gravatar.com\/avatar\/699f56f41e3cf71837719f31c2109aa3?s=100&d=https%3A%2F%2Fs3.amazonaws.com%2Flaracasts%2Fimages%2Fforum%2Favatars%2Fdefault-avatar-15.png","experience":<"award_count":"0","level":2,"points":"9,910","pointsUntilNextLevel":"90">,»achievements»:[],»reported»:null,»staff»:false,»subscribed»:false,»profile»:<"full_name":null,"bio":null,"twitter":"","github":"","website":"","employment":"","job_title":"Software Engineer","location":"","flag":null,"available_for_hire":0>,»dateSegments»:<"created_diff":"3 years ago">,»settings»:<"show_profile":false>,»links»:<"profile":"https:\/\/laracasts.com\/@mdab">>,»replies»:[],»likes»:[],»links»:<"like":"\/comments\/1573\/likes">>,<"id":1848,"video_id":1204,"parent_id":null,"body":"
I tried to use php-cs-fixer and I was impressed. I suggest for those who are using vs code, you should try this.\nPS: For those who are in Windows and want to make a create a new file, you can’t use ‘touch’ like in this video. You can use ‘ni’ command. CMIIW \n»,»strippedBody»:»I tried to use php-cs-fixer and I was impressed. I suggest for those who are using vs code, you should try this.\nPS: For those who are in Windows and want to make a create a new file, you can’t use ‘touch’ like in this video. You can use ‘ni’ command. CMIIW\n»,»bodyInMarkdown»:»I tried to use php-cs-fixer and I was impressed. I suggest for those who are using vs code, you should try this.\nPS: For those who are in Windows and want to make a create a new file, you can’t use ‘touch’ like in this video. You can use ‘ni’ command. CMIIW»,»path»:»\/comments\/5715″,»relativePublishDate»:»2 years ago»,»edited»:true,»user»:<"id":176983,"username":"ryansinaga","avatar":"\/\/unavatar.now.sh\/github\/ryanderon","experience":<"award_count":"0","level":5,"points":"23,920","pointsUntilNextLevel":"1,080">,»achievements»:[<"id":16,"name":"Ten Thousand Strong","description":"Earned once your experience points hits 10,000.","level":"intermediate","icon":"ten-thousand-strong.svg">],»reported»:null,»staff»:false,»subscribed»:false,»profile»:<"full_name":null,"bio":null,"twitter":"","github":"ryanderon","website":"","employment":"","job_title":"Software Engineer","location":"","flag":null,"available_for_hire":0>,»dateSegments»:<"created_diff":"2 years ago">,»settings»:<"show_profile":true>,»links»:<"profile":"https:\/\/laracasts.com\/@ryansinaga">>,»replies»:[],»likes»:[],»links»:<"like":"\/comments\/5715\/likes">>,<"id":7136,"video_id":1204,"parent_id":null,"body":"
It also looks good: \n
Php cs fixer is not working with php 7.4 \n
Error : PHP needs to be a minimum version of PHP 5.6.0 and maximum version of PHP 7.2.*. \n
Настройка редактора Visual Studio Code для разработки на PHP
Пора перейти от слов к действиям и познакомиться с Visual Studio Code поближе. В этом посте представлена поэтапная настройка VS Code для разработки на PHP.
Если кратко, то мы поговорим о том как:
Скачайте и установите Visual Studio Code
Visual Studio Code — бесплатный кроссплатформенный, легковесный редактор кода от Microsoft. Пока он будет загружаться (в нем всего 42 мегабайта), рассмотрим подробнее каждое из этих свойств:
Кроме того, VS Code — это проект с открытым исходным кодом. Вы можете принять участие в разработке или отправлять сообщения о проблемах через репозиторий на GitHub.
После загрузки установите редактор на своем компьютере. Подробные инструкции по установке доступны здесь. Теперь можно открыть окно командной строки, запустить Visual Studio Code и начать редактировать файлы в папке.
Встроенные функции работы с PHP
VS Code поддерживает множество языков, в том числе PHP. На портале Visual Studio Marketplace доступны расширения VS Code, обеспечивающие поддержку дополнительных языков. Для PHP работает подсветка синтаксиса, определение парных скобок и фрагменты кода.
Когда вы начнете набирать код в файле PHP, то заметите автоматическое срабатывание цветового выделения синтаксиса, определения парных скобок и функции IntelliSense.
Настройка статического анализа PHP
По умолчанию VS Code будет проводить статический анализ кода на PHP в ходе проверки при сохранении файла. Для этого используется исполняемый файл php. Если вы работаете с VS Code впервые, то получите сообщение об ошибке, в котором сказано, что исполняемый 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.
Обратите внимание: это расширение использует отладчик XDebug. Поэтому для его работы необходимо установить XDebug. Скачать XDebug можно здесь (для Windows выбирайте 32-разрядную non-thread-safe версию).
Затем внесите в файл php.ini следующие настройки. Я установил XDebug в подкаталог ext установочной папки PHP. Если вы выбрали для XDebug другой каталог установки, убедитесь, что параметр zend_extension содержит правильное значение.
Убедитесь, что корневой раздел веб-сервера соответствует вашему проекту. Тогда при каждом запросе файла PHP XDebug будет предпринимать попытку подключения к порту 9000 для отладки.
Чтобы начать отладку, откройте вкладку Debugging в VS Code.
Щелкните значок шестеренки, чтобы сформировать файл launch.json, который позволит VS Code начать сеанс отладки XDebug.
Чтобы начать отладку, нажмите F5 или щелкните зеленую стрелку на вкладке Debugging. Чтобы задать точку останова в исходном коде, выберите строку и нажмите F9.
Теперь, когда вы откроете определенную веб-страницу, VS Code остановит выполнение исходного кода в заданной точке. В области слева отобразится информация о переменных, стеке вызовов и т. п.
How to run PHP in Visual Studio Code in 2021?
You can find the XAMPP installer on the following permalink:
https://www.apachefriends.org/index.html
Go to the xampp\htdocs folder and create a new folder (with your project name)
Congratulations you have successfully created and run your first PHP code using visual studio code🎉.
You can also check my youtube video “how to run PHP in Visual Studio Code in 2021” if any doubt.👇
Discussion (2)
I have just moved to VS Code from Eclipse. Eclipse had a nice feature where you can connect a server to the XAMP/htdocs folder and it would sync to that folder which means that you can keep your source separate from the deployment folder. A nice feature would be to be able to run a script from within VS Code that did the deployment automatically.
Visual Studio Code + WSL: Running PHP Intellisense from Alpine Linux on Windows 10
Today I open my Visual Studio Code editor, on Windows 10, and it complained that it could not find PHP.
I know that I do not have PHP installed on Windows.
Nor am I remotely interested in doing it.
Not now. Today. Yesterday. Tomorrow… Ever. You get the point.
But it’d be nice to have PHP auto-complete in Visual Studio Code. I need that. Want that.
Visual Studio Code says: “point me to the path where you have PHP installed”. That is, the PHP binary.
So today I decided to take a different tack.
And It all starts here:
TL;DR: yes — it is possible to use Windows Subsystem for Linux for Visual Studio Code development. After all, they’re both Microsoft projects.
Currently I use WSL Ubuntu to run my Docker Compose workloads.
My Docker daemon itself is running on Docker for Windows, to which WSL Ubuntu connects to.
In order to establish separation of concerns, I am keeping my WSL Ubuntu clean of any project dependencies, lest I run into any conflicts with the Docker Compose client itself.
Therefore, in today’s project I am going to attempt installing PHP inside WSL Alpine.
I already downloaded and installed Alpine WSL from the Windows Store, so you can go there to read on how to do that if you need to, I’m not covering WSL install here.
So anyways, I started Dockerizing …
I open Visual Studio Code “inside” WSL: Alpine, then install PHP inside Alpine:
These are the commands for installing PHP in Alpine:
After restarting Visual Studio Code, I notice this little popup on the bottom right-hand corner of the editor:
The PHP Language Server server crashed 5 times in the last 3 minutes. The server will not be restarted.
Here are two related Github issues:
Which mention checking the developer tools console inside VSC. But how do I check the developer tools:
Since VSC is developed using electron, it shouldn’t be surprising that a Chrome Developer Tools window opens:
Is this relevant? Will it show PHP errors related to VSC extensions?
Clicking on the Console tab of the dev tools window reveals the answer:
YASSS. I can see which errors PHP is throwing. Seeing errors gets me excited, it’s a good omen. If I see an error, then it means I can research and fix it. If it fails and I don’t see error, well…
There’s quite a few laundry list here of things to fix:
But nothing too spooky, not for me anyways.
Since this is a fresh WSL Alpine install running on Windows 10, it looks like we have some housekeeping to do. Or rather, housewarming party.
Here’s the JSON error, for the bots:
I head over to the Amazon.com or Alibaba (I’ve never used Alibaba) of Alpine packages:
This should satisfy the JSON dependency:
On my beautiful, integrated VSC terminal, which is connected to the WSL Alpine distro, I can easily add the package:
Next up on the install list, is XDebug:
Given that today is 2020–01–28, that build date of 2020–01–16 is refreshingly … more fresh than Fresh Prince. It feels good to be using Alpine in 2020.
The command here is:
The third thing VSC is babbling about is a missing Git install.
Here’s the package:
The build date of 2020–01–14 is also super fresh. Nice!
The command I use is:
Partial success! The previous notices seem to be gone. But now there’s a new one:
A Google search for this
Call to undefined function token_get_all()
Leads to a Drupal post. Oh the sweet irony. I am using my stack for Drupal, after all:
Seems related to some PHP tokenizer extension. There’s an Alpine module for that.
F1. Reload Window. No popups from the PHP extension!
Let’s check the logs, shall we?
F1. Toggle Developer Tools.
Look Ma’, no errors!
Well, not quite. Looks like XDebug is still needed locally? That’s odd though. Because I can XDebug PHP running in containers using VSC, without having PHP installed on Windows (and XDebug, by extension).
Just out of curiosity, what happened when I installed the XDebug extension in Alpine:
So it’s installed, but not enabled.
From the VSC integrated terminal:
Then, uncomment the extension:
F1. Reload Window. These are the results:
This seems to be related, even though there’s no reason to believe any of the commentariat over at Github are using an exotic WSL setup, not two years ago anyways:
I should have mentioned this earlier, but my current settings.json for VSC have the following added to them:
Create launch.json
This is a fresh environment, so there is no Git setup, or launch.json for VSC, yet.
To create one properly I can copy pasta it from any other project, but that would defeat the purpose of this story. So to create it properly:
Then select PHP
With PHP and PHP dependencies installed in Alpine Linux WSL, Visual Studio Code ready to launch with launch.json (see what I did there?) configured, and Docker for Windows already configured with custom container stack, it’s time to bring the bacon home.
Bringin’ The Bacon Home
In my local setup
I check from WSL Ubuntu that my stack is up and running:
Check that the stack is actually working:
In my Visual Studio Code — WSL Alpine window — I have my Drupal application.
I’m going to set up a breakpoint in sites/default/settings.php because I know it always get hit as part of the Drupal bootstrap process, barring anonymous user or caching use cases, which we’re not dealing with here.
With those pre-flight checks done, press F5 in Visual Studio Code to initiate a debugging session. The debugging view shows up:
And the pause button is active, indicating we’re waiting for a connection/request to happen:
Suspense …
After reloading localhost on the browser, nothing happens…
Using Visual Studio Code — WSL requires revisiting some assumptions about xdebug configuration.
WSL is different. It’s not really the native Windows host running Visual Studio Code, from a networking perspective. You see, xdebug needs to know where it’s connecting to when debugging.
Usually I have my xdebug remote_host parameter pointing to host.docker.internal when using Docker for Windows/Mac.
But when running Visual Studio Code, as a WSL window, that’s not where the xdebug client is located. The xdebug client is now not located on the Windows or Mac host. It’s located inside the Windows Subsystem for Linux — in it’s own little world. At least from a networking perspective.
So I need to give xdebug on the server ( Docker for Windows) the phone number, or instagram handle, so to speak — of the xdebug client on Visual Studio Code ( Windows Subsystem for Linux, Alpine Distro).
If I check my docker compose logs for the PHP FPM service, I get likely confirmation of this theory:
Since I pipe my xdebug configuration from Docker Compose’s YAML files into the PHP container itself, all I need to do is adjust my docker compose configs.
Here’s a good article I found detailing some of that process:
That article contains a lot of technical goodies related to Windows, xdebug, VSC, and WSL 2. It may be worth saving it in some capacity other than a bookmark in case it is lost to Time. Or the Internets.
Which is why I have it set to 0 on my docker compose configuration, along with a healthy helping of comments to warn the weary traveler:
If I look at my local networking stack for Windows, and Windows WSL, I see that the WiFi adapter address is shared in what looks like a bridge configuration. But the WSL contains an ethernet address while Windows does not. I need to talk to the WSL ethernet address.
To test that it works, I can use telnet.
I don’t have telnet installed on my Windows machine. But it’s installed on WSL Ubuntu. So I can use that to ping WSL Alpine, from where the VSC xdebug client is running, and see if it’s responding:
So if WSL Ubuntu can talk to WSL Alpine on 192.168.201.33:9000 via telnet, then should xdebug running inside a container, inside Docker for Windows.
Restart docker compose stack, and listen for php-fpm logs:
Initiate debug session at Visual Studio Code (waiting for connection):
Then visit localhost on my browser to trigger the xdebug debugging session:
Now Visual Studio Code’s xdebug client is successfully talking to the xdebug module of Docker for Windows’ PHP-FPM container:
About that error message tho.
Here is my /etc/wsl.conf :
While this doesn’t necessarily means it’s the root cause for that file not found error, I edit wsl.conf and restart my Windows machine, nonetheless.
One of the things that jumped at me from the error message is the duplicate app/app path of the file not found.
Currently my launch.json has the following:
Modifying it to:
and re-initiating the debug session resolved the issue.
Here’s two screenshots of Visual Studio Code debugging Drupal 8 in all it’s glory:
Notice the little yellow bar at the bottom of VSC saying that this is running from a WSL: Alpine instance:
And a closer look at the call stack:
The After Action Report (AAR)
I try to document as much as I can, as I go. Mostly for my future self, but also for the potential benefit of hapless technically masochistic souls. Either way, I hope this was helpful. I know it was productive for me!
Format HTML in PHP
rifi2k
Format HTML in PHP
Formatting for the HTML code in PHP files.
This extension provides formatting for the HTML code in PHP files. This way this works is this extension runs right before the save action which triggers any other registered PHP formatting extensions so you are free to have one and this will not get in the way or block it.
Supported Features
There are multiple issues and Stackoverflow posts about not being able to format the HTML in PHP files and none of the solutions proposed anywhere really worked 100% so I decided to fix it.
Issues, Ideas, Feature Requests? Go ahead and add them. I’m down to help, add, or fix anything because I know this is badly needed for a lot of PHP / WordPress devs and was a major annoyance for me.
Using This Extension
Keybinding
CTRL + ALT + F
You can change this if desired through the standard Keyboard Shortcuts (File > Preferences > Keyboard Shortcuts) option screen the name is «Format HTML in PHP».
Context Menu
Within a PHP file you can right click and there is a menu option to Format HTML in PHP.
Format On Save
Turn on format on save either globally or scoped to PHP.
HTML Settings
Here is the list of native vscode settings I pass to JS Beautify which control how your HTML will be formatted. You can change any of these to configure how the HTML will be formatted.
PHP executable not found. Install PHP 7 and add it to your PATH or set the php.executablePath setting
I’m running windows 10 fresh copy and I just installed visual studio code. I was trying to develop a PHP project using VS Code. But I’m having trouble in setting up the environment.
I saw a blog post and I downloaded the binary file of PHP 7 and place it in the «C» drive. Then I set path variable too.
But still, I’m getting this issue.
9 Answers 9
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Just like below image.
For those who are using xampp:
This one also works
Remove the «php.executablePath» line from the VS code settings.
Then add the xampp php path to the System variables
After that restart the Visual Studio Code
After adding php directory in User Settings,
If you still have this error, please verify you have installed :
64-bit or 32-bit version of php (x64 or x86), depending on your OS;
some librairies like Visual C++ Redistributable for Visual Studio 2015 : http://www.microsoft.com/en-us/download/details.aspx?id=48145;
To test if you PHP exe is ok, open cmd.exe :
If PHP fails, a message will be prompted with the error (missing dll for example).
Method 2-
In VS Code
Open ‘settings.json‘ file and put the below codes.
If you are using WAMP put this code and Save.
If you are using XAMPP put this code and Save.
Настройка редактора Visual Studio Code для разработки на PHP
Содержание
Visual Studio Code – популярный бесплатный редактор кода. Может с легкостью конкурировать с PhpStorm, ведь он бесплатный и с открытым исходным кодом
Так может выглядеть интерфейс редактора после установки расширений
Основные возможности
VS Code имеет большое количество расширений для разработчика. Для установки нового пакета зайдите во вкладку “Extensions”, введите название пакета в строке поиска, нажмите кнопку “Install”.
EditorConfig for VS Code
PHP Intelliphense
В редакторе уже есть поддержка синтаксиса и подсказок стандартных функций языка. Но без специального дополнения редактор не будет подсказывать пользовательские функции из других частей проекта. Поэтому для поддержки автодополнения, анализа кода, перехода к месту, где создана функция/класс/переменная (с помощью шотката Alt+Click ), используется дополнение PHP Intelliphense
PHP Debug
При разработке может возникнуть ситуация, когда простых функций отладки и логирования становится недостаточно. Тогда может помочь специальный инструмент — Дебаггер. Для PHP есть расширение xdedug, которое позволяет расставить точки останова и посмотреть окружение в предполагаемом месте ошибки, выполняя код поэтапно либо до следующей точки.
Это настройки для локальной разработки, когда проект разрабатывается и запускается на одном компьютере, например на вашей рабочей машине
PHP Sniffer
В языках программирования есть понятие стиль кодирования. Но не все разработчики знают об этом. Программа, которая отвечает за проверку на соответствие стандартам, называется линтер. В PHP приняты стандарты под названием PSR. Нас интересуют стандарты PSR-1 и PSR-12. Именно эти два стандарта касаются кодирования и правил оформления.
В PHP в качестве линтера используется PHP_CodeSniffer. Для его работы необходимо установить глобально сам линтер composer global require «squizlabs/php_codesniffer=*» и расширение PHP Sniffer.
Проверьте, что линтер установился:
Semicolon Insertion Shortcut
Extra
Список расширений, которые могут быть использованы не только для PHP:
GitLens — в VS Code уже встроена поддержка Git. Но когда базовых возможностей становится недостаточно, на помощь может придти Gitlens. Например, одна из полезных фич — git blame на текущей строке.
Indent Rainbow — разноцветные отступы в коде. Подсвечивает некорректный отступ. Можно вместо радуги установить оттенки серого.
Settings Sync — плагин, позволяющий синхронизировать настройки редактора между разными компьютерами. В качестве облачного хранилища используется Github Gists. Все настройки можно скачать, указав нужный файл синхронизации.
Fira Code — моноширинный шрифт, в котором используются лигатуры (объединяет несколько символов в один) для общих комбинаций символов в программировании. Визуальная надстройка для более удобного чтения кода.
16/12/2018 21:36VsCode — это кроссплатформенный редактор исходного кода, разработанный компанией Microsoft.Распространяется бесплатно как программное обеспечение с открытым исходным кодом.Функциональность редактора без проблем можно расширить с помощью плагинов.Благодаря плагинам данный редактор приобретает множество полезных возможностей, что позволяет VsCode составить конкуренцию платным редакторам.Первым шагом необходимо установить сам редактор VsCode.Для этого необходимо перейти на официальный сайт VsCode, скачать редактор и выполнить установку.После того как установка будет завершена, запускаем редактор и переходим в раздел «Расширения«(Extensions).
Теперь благодаря строке поиска ищем необходимые плагины.Список плагинов, который позволит нам расширить функциональные возможности редактора для Web разработки на языке PHP:
В документации к плагину, так-же рекомендуется отключить встроенный в VsCode PHP IntelliSense, чтобы избегать повторяющиеся предложения.Для этого в настройках необходимо отключить конфигурацию:
Для отключения необходимо заменить true на false.Результат:После завершения установки данного плагина вам будет доступно:
Данный плагин можно настроить под личные требования.Для этого нужно зайти в настройки и в поисковой строке написать «minify».По умолчанию можно настроить минимизацию для всех 3х типов файлов (css, js и html). Со списком всех настроек можно ознакомиться на официальном сайте разработчика.
Данный набор значительно улучшает и упрощает работу с кодом.На VsCode есть так-же множество интересных плагинов, которые стоит попробовать.Найти и установить необходимые вам плагины вы можете без проблем и сами в хранилище плагинов, которое доступно прямо в самой IDE в разделе «Плагины«(Extension).Всем спасибо! В комментариях вы можете поделиться своим набором плагинов для VsCode.PhpStorm / vscodeАвтор оригинала: Nick J Trogh
Всем привет! Пора перейти от слов к действиям и познакомиться с Visual Studio Code поближе. В этом посте представлена поэтапная настройка VS Code для разработки на PHP. Если кратко, то мы поговорим о том как:
Скачайте и установите Visual Studio Code
Visual Studio Code — бесплатный кроссплатформенный, легковесный редактор кода от Microsoft. Пока он будет загружаться (в нем всего 42 мегабайта), рассмотрим подробнее каждое из этих свойств:
Встроенные функции работы с PHP
VS Code поддерживает множество языков, в том числе PHP. На портале Visual Studio Marketplace доступны расширения VS Code, обеспечивающие поддержку дополнительных языков. Для PHP работает подсветка синтаксиса, определение парных скобок и фрагменты кода. Когда вы начнете набирать код в файле PHP, то заметите автоматическое срабатывание цветового выделения синтаксиса, определения парных скобок и функции IntelliSense.
Настройка статического анализа PHP
По умолчанию VS Code будет проводить статический анализ кода на PHP в ходе проверки при сохранении файла. Для этого используется исполняемый файл php. Если вы работаете с VS Code впервые, то получите сообщение об ошибке, в котором сказано, что исполняемый 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. Обратите внимание: это расширение использует отладчик XDebug. Поэтому для его работы необходимо установить XDebug. Скачать XDebug можно здесь (для Windows выбирайте 32-разрядную non-thread-safe версию). Затем внесите в файл php.ini следующие настройки. Я установил XDebug в подкаталог ext установочной папки PHP. Если вы выбрали для XDebug другой каталог установки, убедитесь, что параметр zend_extension содержит правильное значение.
Убедитесь, что корневой раздел веб-сервера соответствует вашему проекту. Тогда при каждом запросе файла 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.
Visual Studio Code как альтернатива PHPStorm для Backend-разработчика
В сложившейся ситуации с покупкой продуктов JetBrains на территории РФ задумался об альтернативе одному из их продуктов PHPStorm. Давно слышал много хороших отзывов о VSCode и решил попробовать поработать в нем недельку. Начал с изучения доступных расширений и их настройки. В итоге мне удалось собрать под себя очень достойную альтернативу PHPStorm. В чем-то она хуже, в чем то лучше продукта от JetBrains, но для себя я решил пока остаться на VSCode. Ниже я поделюсь с вами расширениями, которые использую и настройками.
При желании можно установить языковый пакет, который локализует интерфейс приложения.
Установка расширений
Менеджер проектов
По умолчанию в VSCode нет привычной работы с проектами, но эту проблему легко решить используя расширение Project Manager. Чтобы создать проект открываем папку с файлами, которую хотим использовать как проект, нажимаем ctrl+shift+P, в появившейся строке вводит Project и выбираем выделенный ниже элемент списка.
Будет предложено ввести имя проекта.
После подтверждения проект будет создан и его можно будет увидеть в разделе с проектами.
При клике на проект VSCode сразу откроет папку, к которой был привязан проект.
Расширения для PHP
Для комфортной работы с PHP необходимо установить эти расширения:
Если включить одновременно IntelliSense и Intelephense, то будут задвоены подсказки методов и аннотации с описанием функций.
После установки расширений нужно отключить базовые подсказки PHP VSCode. Для этого нужно в расширениях в поисковой строке ввести @builtin php и отключить расширение PHP Language Features.
Расширения для Symfony
Расширения для Laravel
Работа с тэгами
Для удобства работы с HTML, XML и прочими документами с тэгами:
Встроенный Rest Client
Rest client по аналогии с тем, что был добавлен в PHPStorm
REST Client.
Работа с проектом по FTP/SFTP
Для работы с проектами на удаленных машинах нужно установить расширение SFTP. Оно добавляет возможность в проектах добавлять SFTP конфиг, в котором можно указать опции синхронизации.
Системы контроля версий VCS
Для работы с Git, пожалуй, лучшее расширение GitLens — Git supercharged.
Для отображения веток в виде графа Git Graph.
Для удобного просмотра истории Git History.
Для работы с GitLab и проведения CodeReview есть хорошее официальное расширение GitLab Workflow.
Есть еще интересный проект New Relic CodeStream, но мне не нравится, что там нужна регистрация и части кода, который комментируется, сохраняются на их серверах.
Верстка и шаблонизаторы
Для быстрого составления HTML Emmet
Для поддержки синтаксиса TWIG Twig Language 2
Для удобной работы с CSS CSS Peek
Работа с СУБД
Для работы с СУБД из VSCode SQLTools Есть драйвера для всех популярных СУБД (ставятся отдельными расширениями).
Работа с Docker
Для удобной работы с контейнерами, сетями, образами, voluems и т.д. есть отличное расширение от Microsoft Docker.
Документация
Для работы с Markdown markdownlint
Для предпросмотра Swagger прямо в IDE Swagger Viewer
Автоподсказки для написания Swagger Swagger Snippets
Форматирование и читаемый вид
Крутое расширение для форматирования и работы с XML от RedHat.
При нажатии правой кнопкой мыши в открывшемся меню появится новый блок для форматирования после установки расширения.
Альтернатива расширениею выше для работы c XML.
Форматирование JSON JSON Tools
Для форматирования нужно использовать комбинации славишь ниже:
Форматирование SQL SQL Formatter
При нажатии правой кнопки мыши по выделенному SQL в меню появится новый блок после установки расширения.
TODO и FIXME
Работая с PHPStorm многие из вас привыкли к удобному просмотру TODO и FIXME в виде списка по всему проекту. В VSCode для этой задачи есть два расширения.
Работа с таск-трекерами
Для быстрой работы с задачами прямо из VSCode для себя использую эти расширения:
В магазине VSCode есть большой выбор тем. Мне больше всего нравится во всех IDE Twilight Twilight Theme Многим нравится GitHub Theme. В целом в магазине каждый найдет что-то на свой вкус.
Если вы обычно работаете с несколькими окнами VSCode одновременно, то вас может заинтересовать расширение Peacock, которое позволяет задать окнам IDE разную палитру и проще ориентироваться в открытых проектах.
Прочее
Настройки
Посе установки всех необходимых расширений необходимо произвести некоторые настройки в самом settings.json VSCode и в проектах настроить файлы-конфигурации расширений для их использования.
Базовые настройки VSCode
Для комфортной работы расширений нужно произвести настройки в главном settongs.json.
Для открытия его редактирования нужно набрать ctrl + shift + P и в строке ввести settings.json.
В выпадающем списке выбрать выделенный на скрине вариант.
Откроется глобальный settings.json для всего VSCode, в котором нужно добавить / обновить значение узлов, как показано ниже.
Exit fullscreen mode
Настройка SFTP / FTP подключения в проекте
Для настройки SFTP / FTP подключения в проекте нужно создать файл-конфигурацию sftp.json в проекте. Для этого нужно набрать ctrl + shift + P, в строке ввести SFTP: Config и выбрать выделенный ниже элемент списка.
Оптимальный файл-конфигурации приведен ниже.
Exit fullscreen mode
Для скачивания проекта файлов с сервера нужно ввести SFTP Download и выбрать выделенный ниже элемент списка.
При нажатии правой кнопкой мыши по файлу в дереве файлов в открывшемся меню есть блок скачки и выгрузки файла на сервер.
Настройка SQLTool
Для добавления подключения к СУБД нужно нажать ctrl+shift+P, в строке ввести SQLTool и выбрать выделенный ниже элемент списка.
Откроется ассистент настройки подключения
В итоге будет получен settings.json файл с параметрами подключения.
В одном проекте может быть несколько подключений к разным БД.
Для MySQL файл-конфиграции выглядит как приведено ниже.
Exit fullscreen mode
Настройка расширения XDebug
Для отладки PHP кода средствами Xdebug нужно составить файл-конфигурацию.
Для этого в меню Run нужно выбрать Add Configuration.
Откроется редактор launch.json.
Пример заполненного файла конфигурации для xdebug приведен ниже.
Exit fullscreen mode
По итогу работа отладчика будет выглядеть, как на скрине ниже
Настройка расширения Redmine
Exit fullscreen mode
Настройка расширения Intelephense
Чтобы указать версию PHP у проекта для корректной работы линтера нужно в файле settings.json в проекте указать ее, как показано ниже.
Exit fullscreen mode
Спасибо, что дочитали до конца! Надеюсь, моя инструкция будет полезна и вам!
Как запустить php server в vs code?
Поясните пожалуйста начинающему в php, что требуется сделать, чтобы запустить расширение PHP Server в VS CODE.
При запуске расширения всплывают окна с ошибками:
Ошибки отсылают к файлу settings.json:
У меня php установлен отдельно. В нете есть статьи как поставить php на windows
Обязательно добавьте путь к исполняемому файлу php.exe в переменную PATH в настройках windows
Прописываете путь к Вашему исполняемому файлу php
Теперь при сохранении файла VSCode сам будет проверять его на ошибки php
tommcfarlin/phpcs-wpcs-vscode
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
PHP CodeSniffer and WordPress Coding Standards with VS Code
Last Updated 2020-07-31 by @tommcfarlin
This guide is meant to provide all of the steps necessary to easily get up and running with PHP CodeSniffer, the WordPress Coding Standard ruleset, and Visual Studio Code.
All of the resources used in this guide are linked at the bottom. This guide is also licensed MIT. If you’d like to contribute, then please feel free to open issues or issue pull requests. I’ll be happy to merge them and also add your username to CONTRIBUTING.
If you’re looking for corresponding blog posts, please see:
As always, don’t forget to checkout the CHANGELOG to track everything that’s changed since the initial release of this guide.
1. Verifying PHP
The following steps assume you have PHP installed and globally accessible on your system. You can test this by entering the following command in the terminal:
And you should see something like this:
If you’re looking for how to use a different version of PHP installed elsewhere on your system, this is not the guide for that. If, however, you’re curious as to where the version of PHP you’re using is stored, you can enter:
And you should see something similar to this:
That should give you enough information for the rest of this guide.
2. Installing Composer
Installing Composer globally means that you’ll be able to access it from anywhere on your system (that is, in any directory regardless of where you are). To do this, you can read the manual or follow the quick steps below (which summarize the manual, anyway):
And now you can access Composer from anywhere in your system. To do try it out, enter the following command in your terminal:
You should see something like this:
With Composer globally installed, you can now install the WordPress Coding Standards rules.
3. Installing PHP CodeSniffer
For the purposes of this document, we’re installing PHP CodeSniffer on a project-by-project basis. To do this, we’re going to be using Composer.
From the integrated terminal within Visual Studio Code, enter the following command:
4. Installing the WordPress Coding Standards Rules
I recommend placing the rules in a directory you can refer to often. Personally, I use a projects directory to manage all of my work.
This will create a wpcs directory in your projects directory and it makes it easy to tell each project where the WordPress Coding Standards are stored because, remember, we’ll be using Composer on a project-by-project basis.
5. Tell PHPCS About WPCS
From within Visual Studio’s integrated terminal, make sure that you’re in your project’s directory and then issue the following command:
And this will tell your project’s copy of PHPCS where the WordPress Coding Standards are.
6. Update User Settings
Make sure the file looks like the following (though you may need to tweak based on your existing settings)
And this will enable PHPCS and will also tell it to use the standard WordPress ruleset. If this doesn’t start working on the code your have automatically, then restart Visual Studio Code.
About
How to install PHP CodeSniffer and the WordPress Coding Standard Rules in Visual Studio Code.
PHP Programming in VS Code
Visual Studio Code is a great editor for PHP development. You get features like syntax highlighting and bracket matching, IntelliSense, and snippets out of the box and you can add more functionality through community created VS Code extensions.
Snippets
Visual Studio Code includes a set of common snippets for PHP. To access these, hit kb(editor.action.triggerSuggest) to get a context specific list.
Linting
There are three settings to control the PHP linter:
To set the PHP executable path, open your User or Workspace Settings and add the php.validate.executablePath :
Extensions
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.
Next Steps
Read on to find out about:
PHP DocBlocker
Neil Brayfield
PHP DocBlocker
Basic PHP DocBlocking extension.
We now have a set of unit tests and some full coverage on the parsing of signatures as well as continuous integration. This should ensure the extension remains stable as development progresses.
Features
Requirements
This extension has no dependencies.
Extension Settings
This extension contributes the following settings:
Templating
Default set up for function
The below is the default set up for a function. The order of the keys represents the output order. There are no specific options in each config option per key to add additional control.
Supported template keys
Key | Aplies to type | Description |
---|---|---|
message | All | Space for entering a description of your block |
extra | All | Adds in your custom tags from the extra config |
param | Function | Function @param items |
return | Function | Function @return item |
var | Property | Property @var item |
* | All | This is for any key that is unmatched you can use the content option to add a tag |
Supported template config options
Option | Aplies to key(s) | Description |
---|---|---|
gapBefore | All | Adds a gap before the tag section starts |
gapAfter | All | Adds a gap after the tag section ends |
content | * | Adds a gap after the tag section ends |
Configured function template example
In the example below we have added some gap configuration and removed the return tag for our template as well as changing the default order. This means we’ll never have a @return tag and extra comes before the params. It’s also worth pointing out that the gapAfter in the message is the same as setting the gap config option in the main config to true.
Configured function with extra content and placeholders
The example below won’t have a return tag and will add in an author tag with correct placeholders depending on how many options you have. You can put in placeholders by using ### in place of the tab stop number and it will be calculated at generation time.
Supported DocBlock tags
Please see below for a list of supported tags and their snippets. These tags are available within a DocBlock and can be triggered by typing @ then another characted (Provided your vscode settings allow).
Future development
It probably wouldn’t be too much work to expand this to work with multiple languages. If this is something you are interested in, please pop over to github and add your feedback to the issue neild3r/vscode-php-docblocker#17.
Please also feel free to suggest new configuration options, I appreciate at this time the extension is mostly set up for my own DocBlock style requirements but more options could be added for other use cases.
How To Run PHP Code Directly In The Visual Studio Code Console Terminal
It turns out you can run PHP code directly inside VS Code if you hook it up to your local PHP interpreter. No Debug Module Needed! It’s quick and simple to do and is an invaluable tool to have when you want to tinker with your code. Instead of booting up a web server and browser, you can execute instantly without leaving the VS Code IDE.
Prerequisites
To follow this tutorial step-by-step, make sure you have the following in place.
Configuring VS Code To Run PHP Code
So, we’ve got everything together and VSCode open, let’s add the settings.
2. Add the following JSON to the User Settings on the Right Hand Side of the IDE. Replacing C:\\xampp\\php\\ with your path to your php.exe.
It should now look similar to below –
4. Go to your index file and add the following code –
5. Press F5 and VS Code will launch and execute the script. However, if you’ve already got debugging launch settings installed, you will have to explicitly choose ‘Run using local PHP Interpreter‘ from the drop-down list that pops up when pressing F5.
6. The debug console will pop up at the bottom of the IDE and say, ‘Hi Debug Console’. See the image below.
7. That is it! You have successfully set up your local PHP interpreter to execute code directly in VS Code IDE!
Summary
This setup is really great if you want a quick mess around with your code. Without having to configure a web server or any debug modules. It’s a great little gem I’ve stumbled across whilst using this fantastic IDE. I hope it helps you too!
PHP Development Essentials
Jill M. Nolan
PHP Development Essentials, a Visual Studio Code extension package
Background
Are you tired of reinstalling extensions on each of your computer(s)? How about when you have to reset computer entirely? Or, how about you’re an instructor, a hobbyist, or just «getting your feet wet» in the fine craft of PHP development who does not know which extension(s) to select to get the job done both efficiently and effectively. Regardless, please do not waste time and energy on something so tedious as a process of installing extensions. Extensions are, in a word, awesome! Their premise is to extend the features and functionality of Visual Studio Code.
Visual Studio Code Tips and Tricks from its Docs
Please puruse the VSCode Variables Reference, if you wish to use variables substitution.
VSCode Keyword Shortcuts
Please puruse the VSCode Keybindings, if you wish to use custom keybindings.
Please puruse the VSCode Tips and Tricks to make your experience a little bit more enjoyable.
Relevant Language Specific Documentation, if you’re a nerd like me. 🙂
What extensions will I get by selecting this extension package?
Glad, that you’ve asked! Please find the supervening extensions and subsequent «themes» as well. Of course, I always love to hear your suggestions to improve this extension package. To do so, please create a new issue in the Issues Section. After all, the ultimate goal for this extension pack is convenience at the click of one button.
Themes
Extensions
Collaboration & Productivity
Language Support
CSS/Bootstrap/SCSS/Mocha
JavaScript
TypeScript
Markdown
PHP & WordPress
Composer: Provides an interface to Composer dependency manager for PHP. Likewise, it provides schema validation for composer.json configuration files.
Elementor Snippets: Code snippets to build Elementor Plugin widgets.
phpcs: This linter plugin for Visual Studio Code provides an interface to phpcs. It will be used with files that have the “PHP” language mode.
PHP DocBuilder: A simple, dependency free PHP-specific DocBlocking package.
REST Client: Allows you to send HTTP request and view the response in VS Code directly.
WordPress Snippets: A collection of WordPress snippets and autocompletions for VS Code.
WordPress Toolbox: The ultimate collection of snippets for every WordPress function, class and constant, complete with argument type hints and brief descriptions, within VS Code.
Note: Please be advised that the WordPress Extension Pack recommends standalone installation of the WordPress Coding Standards for PHP_CodeSniffer, which is a collection of PHP_CodeSniffer rules («sniffs») to validate code developed for WordPress. These sniffs ensures code quality and adherence to coding conventions, specifically the official WordPress Coding Standards.
Notes
It is my pledge to update this Extension Package with update extension as needed to perform the job efficiently and effectively. Likewise, the Extensions list will be categorized accordingly and more detailed information regarding plugins will be incorporated in the near future. I will certainly be on the lookup for some helpful Web Development hints and tips to make your experience enjoyable. Cheers! 🙂
Debug Overview
Debugging of PHP code in VS Code allows for inspecting a PHP program, inspecting actual variables, stack traces, exceptions, breaking and stepping through the code, debugging PHPUnit tests, and more.
Requirements
In order to debug a PHP program, you need PHP (either installed locally or on your server) together with Xdebug extension.
Local PHP Installation
In case there are more PHP installations on the system, see choosing PHP Version and select the right one.
To verify your PHP and Xdebug are installed correctly:
If PHP with Xdebug is installed correctly, you will see
php.ini Configuration
Xdebug needs to be set in php.ini file that corresponds to your PHP installation.
Server PHP Installation
This applies to the situation when PHP is not running on your local system but it’s on a Cloud, Web Host, Docker, Xampp, etc.
In case php itself is not running on your local system, consult the installation of PHP+Xdebug with the specific server host.
You can then take advantage of DBGP Proxy to allow multiple users to debug the same site safely.
Launching Debug in VSCode
With launch.json
Debugging can be started without any configuration. This is recommended if you just need to attach to an existing Web Server (with Xdebug configured) or to quickly run and debug a PHP script.
Features
The debugging features are the following:
Debug Adornments
When stepping through the code, the editor will display values of variables and expressions corresponding to the current statement. Values are also shown for the enclosing scopes such as loop control variables, switch expression, and function parameters.
Start Debug and Stop on Entry
Open command palette and run Start Debugging and Stop on Entry (aka Step Into). The command launches debugging and breaks on the first statement.
Troubleshooting
These are steps that should help to diagnose and solve common problems with debugging PHP:
Running the following command should display no warnings, and an Xdebug notice:
Firewall must be properly set up to allow communication through the Xdebug port.
Append the following query parameter when opening the debugged PHP Web Site:
I’m trying to implement other coding standards for phpcs. Currently, I have setup phpcs for visual studio code and I have the following coding standards
I want to set up other standards listed here: php-fig
How do I go about setting these standards for my development?
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Expanding @Vladd’s answer with an example.
Download and save the file to a local directory. For some reason I wanted it to be in the same folder as default phpcs standards (global installation). So I’ve saved it to: C:\Users\USER_NAME\AppData\Roaming\Composer\vendor\wpcs
If you have git setup, you can directly clone the repo to this folder by accessing the folder (vendor), hitting shift+right click and clicking on ‘Open Command Window Here’. Once the command prompt is loaded, just paste this code:
This will clone the standards into a folder called wpcs within your vendor folder.
Once you have the standards downloaded, you’ll need to let phpcs know where to find the new standards. That’s done by this command:
Make sure you change the path to where you have downloaded the standards.
The installed coding standards are MySource, PEAR, PSR1, PSR2, Squiz, Zend, WordPress, WordPress-Core, WordPress-Docs, WordPress-Extra and WordPress-VIP
You can now enable the standard you would like to use for your project. For example. If I want to switch from the default standard to wordpress, I’d use the following command:
Как запускать или отлаживать php в коде Visual Studio (VSCode)
Я не могу найти способ запустить или отладить php в коде Visual studio, кто-нибудь знает, как это сделать?
9 answers
Насколько я читал об этом сегодня, вы не можете отлаживать ничего, кроме node.js, JavaScript и TypeScript на данный момент, но они сказали, что хотят добавить новые языки, которые вы можете отлаживать. Редактор все еще находится в разработке. Тем не менее, я не думаю, что в будущем появится отладчик php, поскольку php находится на стороне сервера, поэтому вы не можете отлаживать его только на своем клиенте.
Если вы хотите отладить php, я могу порекомендовать xdebug.
Обновлено:
Теперь это возможна отладка с помощью VS-кода. Вам необходимо установить xdebug и расширение php-debug для VSCode.
Отладка PHP с помощью VSCode с использованием расширения vscode-php-debug
VSCode теперь может поддерживать отладку PHP-проектов с помощью расширения marketplace vscode-php-debug.
Это расширение использует XDebug в фоновом режиме и позволяет использовать точки останова, часы, трассировки стека и тому подобное:
Установка проста из VSCode: Вызовите командную строку с помощью F1, а затем введите ext install php-debug
По ссылке следующие шаги:
Примечание. В связанной статье приведены конкретные сведения, в том числе значения PHP для вашей конфигурации пользователя VS Code и т. Д.
Стоит отметить, что для работы отладчика необходимо открыть папку проекта в коде Visual Studio. Я потерял несколько часов, чтобы заставить его работать, открыв в редакторе только отдельный файл.
Если вы используете Ubuntu 16.04 и php7, вы можете установить xdebug с помощью следующей команды:
Вы можете найти полный процесс настройки здесь.
И начните отладку в VS-коде с расширением php-debug.
Для отладки php с помощью vscode вам понадобятся следующие вещи:
Вы можете аккуратно пройти шаги 1 и 2, следуя официальному руководству vscode.Полностью рекомендуется использовать Мастер установки xdebug для проверки вашего XDebug конфигурация.
На самом деле возможно запускать PHP без xDebug и без установки каких-либо дополнительных расширений.
Если вы просто хотите, чтобы исполняемый файл PHP оценивал PHP-код и отображал вывод в терминале (т.Е. не в браузере), вам просто нужно скопировать следующую конфигурацию в настройки пользователя:
Теперь скопируйте мою конфигурацию ниже в свои задачи.файл json:
wongjn/vscode-php-sniffer
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Uses PHP_CodeSniffer to format and lint (mainly) PHP code.
And if your projects look like this:
This extension contributes the following settings:
Windows Hanging PHP Process
About
Visual Studio Code extension for PHP_Codesniffer validation and formatting.
INsReady/docker-vscode-php
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Visual Studio Code for PHP
This docker image packages Visual Studio Code ( vscode ) with a curated list of extensions for PHP development. The goal of this image is to offer an easier, faster and free IDE, comparing to PhpStorm.
To launch the «IDE» and set the current folder as the root of your application:
You can set up bash alias for the command above, for example:
To stop the container and auto-remove it: Just use Ctrl+C
Use with other Docker image:
This image would work well with insready/drupal-dev, Xdebug remote debugging will simply work out of box.
Configure Xdebug to work
More documentation on this bit configuration can be fund here.
List of vscode extensions included
You are invited to contribute new features, fixes, or updates, large or small; we are always thrilled to receive pull requests, and do our best to process them as fast as we can.
Before you start to code, we recommend discussing your plans through a GitHub issue, especially for more ambitious contributions. This gives other contributors a chance to point you in the right direction, give you feedback on your design, and help you find out if someone else is working on the same thing.
About
Visual Studio Code in a container for PHP/Drupal development
Using PHP and MySql in VS Code
I would like to run PHP along with MYSql in VS Code as I would run using ‘xammp’. I came across some extensions to use like IIS-Express and vscode-database but don’t know how to configure and link them together.And which PHP would be suitable i.e. Thread safe or non Thread Safe.
PS: I am completely new to learn PHP and VS Code and want to use VS Code for every language I learn 🙂
1 Answer 1
IIS Express is an extension that will basically run your project folder as a website. It’s an extremely handy tool that I couldn’t live without. Usage is simple, and noted below. I should also point out that IIS Express is only available for Windows and will not work on Linux or OSX.
More information can be found here.
After looking around, it seems vscode-database does not host an actual database, but rather, gives you a way to test your queries in the editor. The information page for vscode-database doesn’t make that very clear, though. So for MySQL functionality, you may want to look at running MySQL in a «portable mode». Instructions for this can be found here.
After getting that setup, you would just connect to it in php like any other MySQL database.
phpcbf
Per Soderlind
PHP Code Beautifier and Fixer for Visual Studio Code
This extension provides the PHP Code Beautifier and Fixer ( phpcbf ) command for Visual Studio Code.
phpcbf is the lesser known sibling of phpcs (PHP_CodeSniffer). phpcbf will try to fix and beautify your code according to a coding standard.
Preview
right mouse-click, in context menu, select ‘Format Document’. Here using the WordPress-Core standard. You can also enable formatting on save.
Requirements
phpcbf must be installed. phpcbf is installed when you install phpcs.
I recommend phpcs version 3.2.2 or later.
A quick install is using composer. After installing composer, in your workspace root, run the following command:
composer require «squizlabs/php_codesniffer=*»
Extension Settings
This extension has the following settings:
The default settings are
Coding standards
Available standards
Additional standards
If you add a standard to phpcs, it will be available for phpcbf. Some popular standards are: Drupal, WordPress, Yii2, Magento and Symfony.
Rules file
You can also point to a phpcs.xml rules file, eg: «phpcbf.standard»: «/file/path/phpcs.xml»
Known Issues
None, but this is my first vscode extension, you’re warned 🙂
Release Notes
Credits
I learned a lot reading the code of, and borrowing code from PHP CS Fixer for Visual Studio Code.
Copyright and License
PHP Code Beautifier and Fixer for Visual Studio Code is copyright 2018 Per Soderlind
PHP Code Beautifier and Fixer for Visual Studio Code is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version.
PHP Code Beautifier and Fixer for Visual Studio Code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
How can I format PHP files with HTML markup in Visual Studio Code?
I also tried about five extensions, but none of them do the reformatting.
9 Answers 9
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
The extension Beautify (from HookyQR) just does it very well. Either add PHP, and any other file extension type, to the configuration. As said by Nico, here is an example:
Search for Beautify in the field above. And click on «Edit in settings.json» for «Beautify: Config».
For the «html» section, add «php» and «blade».
You can also add a keybinding to have a keyboard shortcut. Here is how to do it:
Open keybindings.json (go to menu File → Preferences → Keyboard Shortcuts)
Click in the above. Open and edit file keybindings.json
Add the following into the closed brackets, []
Choose any key you want, and make sure you don’t override an existing one. Search first in the left side if it exists or not.
Note that all of those things are well documented in the description of the extension.
Extra: Note about blade
(suite to @Peter Mortensen clarification pinpoint)
blade or blade.php
First if you open the list of languages as by the image bellow:
Well but how to check!
Try with blade.php in the settings!
Try to beautify
You’ll get an asking context menu for what language (html, css, js)!
So it doesn’t works!
How well it works with blade
The awesome answer to that! Is try it, and see for yourself!
But if you ask me! I’ll say it does work as with html! It can be too handy! And you may need to fix some lines! Depending on your expectations and your style!
Here an illustration! I screwed the indentation in purpose
Visual studio code php
Let’s next review the process of traversing your file system. Or, in other words, what is the fastest way to open a file, or a class, or a PHP method. It’s vital that we streamline this workflow as best as we can. «,»excerpt»:»Let’s next review the process of traversing your file system. Or, in other words, what is the. «,»source_code»:null,»keyConcepts»:null,»position»:3,»dateSegments»:<"published":"November 16, 2017","publishedAlt":"Nov 16th, 2017","publishedDiff":"4 years ago","whenAvailableForHumans":"4 years">,»length»:310,»lengthForHumans»:»5:10″,»isNew»:false,»isScheduled»:false,»path»:»\/episodes\/1196″,»taxonomy»:<"name":"Tooling","path":"https:\/\/laracasts.com\/browse\/tooling">,»series»:<"title":"Visual Studio Code for PHP Developers","taxonomy":<"name":"Tooling","path":"https:\/\/laracasts.com\/browse\/tooling">,»thumbnail»:»https:\/\/laracasts.nyc3.cdn.digitaloceanspaces.com\/series\/thumbnails\/visual-studio-code-for-php-developers.png»,»path»:»\/series\/visual-studio-code-for-php-developers»>,»viewingStatus»:<"scheduled":false,"watchable":true,"requiresReactivation":null,"requiresBillingDetails":false,"isCompleted":null>,»hasTranscript»:false,»vimeoId»:»243144512″>,<"id":1197,"className":"Laracasts\\Video","chapter":1,"type":"episode","title":"Vim Keybinding Goodness","body":"
The programming world splits into two groups: those who research Vim keybindings for each new editor they try, and those who are still figuring out how to exit Vim. If you’re among the former, let’s get these keybindings working. «,»excerpt»:»The programming world splits into two groups: those who research Vim keybindings for each new editor they. «,»source_code»:null,»keyConcepts»:null,»position»:4,»dateSegments»:<"published":"November 16, 2017","publishedAlt":"Nov 16th, 2017","publishedDiff":"4 years ago","whenAvailableForHumans":"4 years">,»length»:227,»lengthForHumans»:»3:47″,»isNew»:false,»isScheduled»:false,»path»:»\/episodes\/1197″,»taxonomy»:<"name":"Tooling","path":"https:\/\/laracasts.com\/browse\/tooling">,»series»:<"title":"Visual Studio Code for PHP Developers","taxonomy":<"name":"Tooling","path":"https:\/\/laracasts.com\/browse\/tooling">,»thumbnail»:»https:\/\/laracasts.nyc3.cdn.digitaloceanspaces.com\/series\/thumbnails\/visual-studio-code-for-php-developers.png»,»path»:»\/series\/visual-studio-code-for-php-developers»>,»viewingStatus»:<"scheduled":false,"watchable":true,"requiresReactivation":null,"requiresBillingDetails":false,"isCompleted":null>,»hasTranscript»:false,»vimeoId»:»243149996″>,<"id":1198,"className":"Laracasts\\Video","chapter":1,"type":"episode","title":"Dynamic Snippets","body":"
Please don’t manually type out your various class and method structures. These are perfect use-cases for custom snippets. Let’s create a few together, while reviewing some key variable names to make them more dynamic. «,»excerpt»:»Please don’t manually type out your various class and method structures. These are perfect use-cases for custom. «,»source_code»:null,»keyConcepts»:null,»position»:5,»dateSegments»:<"published":"November 16, 2017","publishedAlt":"Nov 16th, 2017","publishedDiff":"4 years ago","whenAvailableForHumans":"4 years">,»length»:369,»lengthForHumans»:»6:09″,»isNew»:false,»isScheduled»:false,»path»:»\/episodes\/1198″,»taxonomy»:<"name":"Tooling","path":"https:\/\/laracasts.com\/browse\/tooling">,»series»:<"title":"Visual Studio Code for PHP Developers","taxonomy":<"name":"Tooling","path":"https:\/\/laracasts.com\/browse\/tooling">,»thumbnail»:»https:\/\/laracasts.nyc3.cdn.digitaloceanspaces.com\/series\/thumbnails\/visual-studio-code-for-php-developers.png»,»path»:»\/series\/visual-studio-code-for-php-developers»>,»viewingStatus»:<"scheduled":false,"watchable":true,"requiresReactivation":null,"requiresBillingDetails":false,"isCompleted":null>,»hasTranscript»:false,»vimeoId»:»243154313″>,<"id":1199,"className":"Laracasts\\Video","chapter":1,"type":"episode","title":"The Glorious Built-in Terminal","body":"
If you’re accustomed to opening a separate Terminal or iTerm window each time you need to trigger a console command, if you wish, you may now accomplish this directly from Visual Studio Code, via its terminal panel. Ctrl-` is your friend. «,»excerpt»:»If you’re accustomed to opening a separate Terminal or iTerm window each time you need to trigger. «,»source_code»:null,»keyConcepts»:null,»position»:6,»dateSegments»:<"published":"November 16, 2017","publishedAlt":"Nov 16th, 2017","publishedDiff":"4 years ago","whenAvailableForHumans":"4 years">,»length»:95,»lengthForHumans»:»1:35″,»isNew»:false,»isScheduled»:false,»path»:»\/episodes\/1199″,»taxonomy»:<"name":"Tooling","path":"https:\/\/laracasts.com\/browse\/tooling">,»series»:<"title":"Visual Studio Code for PHP Developers","taxonomy":<"name":"Tooling","path":"https:\/\/laracasts.com\/browse\/tooling">,»thumbnail»:»https:\/\/laracasts.nyc3.cdn.digitaloceanspaces.com\/series\/thumbnails\/visual-studio-code-for-php-developers.png»,»path»:»\/series\/visual-studio-code-for-php-developers»>,»viewingStatus»:<"scheduled":false,"watchable":true,"requiresReactivation":null,"requiresBillingDetails":false,"isCompleted":null>,»hasTranscript»:false,»vimeoId»:»243155815″>,<"id":1200,"className":"Laracasts\\Video","chapter":1,"type":"episode","title":"Git Ready","body":"
For the Laravel users among you, the Artisan extension allows you to trigger any artisan command straight for the GUI. This means, within seconds, you can generate and load your new controller. «,»excerpt»:»For the Laravel users among you, the Artisan extension allows you to trigger any artisan command straight. «,»source_code»:null,»keyConcepts»:null,»position»:8,»dateSegments»:<"published":"November 16, 2017","publishedAlt":"Nov 16th, 2017","publishedDiff":"4 years ago","whenAvailableForHumans":"4 years">,»length»:94,»lengthForHumans»:»1:34″,»isNew»:false,»isScheduled»:false,»path»:»\/episodes\/1201″,»taxonomy»:<"name":"Tooling","path":"https:\/\/laracasts.com\/browse\/tooling">,»series»:<"title":"Visual Studio Code for PHP Developers","taxonomy":<"name":"Tooling","path":"https:\/\/laracasts.com\/browse\/tooling">,»thumbnail»:»https:\/\/laracasts.nyc3.cdn.digitaloceanspaces.com\/series\/thumbnails\/visual-studio-code-for-php-developers.png»,»path»:»\/series\/visual-studio-code-for-php-developers»>,»viewingStatus»:<"scheduled":false,"watchable":true,"requiresReactivation":null,"requiresBillingDetails":false,"isCompleted":null>,»hasTranscript»:false,»vimeoId»:»243173158″>,<"id":1202,"className":"Laracasts\\Video","chapter":1,"type":"episode","title":"PHP Automatic Imports","body":"
We’re getting nitpicky at this point, but that’s okay. Having to reach for the mouse to right-click on a symbol to perform any kind of contextual action is a bit annoying. Let’s instead assign a custom keyboard shortcut so that my hands can remain on the keyboard permanently. «,»excerpt»:»We’re getting nitpicky at this point, but that’s okay. Having to reach for the mouse to right-click. «,»source_code»:null,»keyConcepts»:null,»position»:12,»dateSegments»:<"published":"November 16, 2017","publishedAlt":"Nov 16th, 2017","publishedDiff":"4 years ago","whenAvailableForHumans":"4 years">,»length»:93,»lengthForHumans»:»1:33″,»isNew»:false,»isScheduled»:false,»path»:»\/episodes\/1205″,»taxonomy»:<"name":"Tooling","path":"https:\/\/laracasts.com\/browse\/tooling">,»series»:<"title":"Visual Studio Code for PHP Developers","taxonomy":<"name":"Tooling","path":"https:\/\/laracasts.com\/browse\/tooling">,»thumbnail»:»https:\/\/laracasts.nyc3.cdn.digitaloceanspaces.com\/series\/thumbnails\/visual-studio-code-for-php-developers.png»,»path»:»\/series\/visual-studio-code-for-php-developers»>,»viewingStatus»:<"scheduled":false,"watchable":true,"requiresReactivation":null,"requiresBillingDetails":false,"isCompleted":null>,»hasTranscript»:false,»vimeoId»:»243189100″>,<"id":1206,"className":"Laracasts\\Video","chapter":1,"type":"episode","title":"Sweet PHP Debugging in Four Minutes","body":"
The useful \»Import Cost\» extension allows us to automatically visualize the size of each JavaScript dependency we import. It does this by appending a small, non-intrusive label next to each import. Are you importing a massive dependency that you didn’t know about? Well, if you are, this extension will make it crystal clear.»,»excerpt»:»The useful \»Import Cost\» extension allows us to automatically visualize the size of each JavaScript dependency we. «,»source_code»:null,»keyConcepts»:null,»position»:16,»dateSegments»:<"published":"November 16, 2017","publishedAlt":"Nov 16th, 2017","publishedDiff":"4 years ago","whenAvailableForHumans":"4 years">,»length»:141,»lengthForHumans»:»2:21″,»isNew»:false,»isScheduled»:false,»path»:»\/episodes\/1209″,»taxonomy»:<"name":"Tooling","path":"https:\/\/laracasts.com\/browse\/tooling">,»series»:<"title":"Visual Studio Code for PHP Developers","taxonomy":<"name":"Tooling","path":"https:\/\/laracasts.com\/browse\/tooling">,»thumbnail»:»https:\/\/laracasts.nyc3.cdn.digitaloceanspaces.com\/series\/thumbnails\/visual-studio-code-for-php-developers.png»,»path»:»\/series\/visual-studio-code-for-php-developers»>,»viewingStatus»:<"scheduled":false,"watchable":true,"requiresReactivation":null,"requiresBillingDetails":false,"isCompleted":null>,»hasTranscript»:false,»vimeoId»:»243204522″>,<"id":1210,"className":"Laracasts\\Video","chapter":1,"type":"episode","title":"Pour Me a Glass of ESLint","body":"
Let’s supercharge our JavaScript (including Vue templates) error and style guide detection with ESLint. Once installed, you’ll stop and wonder how you were able to code effectively before this wonderful addition to your tool belt. «,»excerpt»:»Let’s supercharge our JavaScript (including Vue templates) error and style guide detection with ESLint. Once installed, you’ll. «,»source_code»:null,»keyConcepts»:null,»position»:17,»dateSegments»:<"published":"November 16, 2017","publishedAlt":"Nov 16th, 2017","publishedDiff":"4 years ago","whenAvailableForHumans":"4 years">,»length»:342,»lengthForHumans»:»5:42″,»isNew»:false,»isScheduled»:false,»path»:»\/episodes\/1210″,»taxonomy»:<"name":"Tooling","path":"https:\/\/laracasts.com\/browse\/tooling">,»series»:<"title":"Visual Studio Code for PHP Developers","taxonomy":<"name":"Tooling","path":"https:\/\/laracasts.com\/browse\/tooling">,»thumbnail»:»https:\/\/laracasts.nyc3.cdn.digitaloceanspaces.com\/series\/thumbnails\/visual-studio-code-for-php-developers.png»,»path»:»\/series\/visual-studio-code-for-php-developers»>,»viewingStatus»:<"scheduled":false,"watchable":true,"requiresReactivation":null,"requiresBillingDetails":false,"isCompleted":null>,»hasTranscript»:false,»vimeoId»:»243226893″>,<"id":1215,"className":"Laracasts\\Video","chapter":1,"type":"episode","title":"Type Checking JavaScript Files","body":"
We’re getting nitpicky at this point, but that’s okay. Having to reach for the mouse to right-click on a symbol to perform any kind of contextual action is a bit annoying. Let’s instead assign a custom keyboard shortcut so that my hands can remain on the keyboard permanently. «,»excerpt»:»We’re getting nitpicky at this point, but that’s okay. Having to reach for the mouse to right-click. «,»source_code»:null,»keyConcepts»:null,»position»:12,»dateSegments»:<"published":"November 16, 2017","publishedAlt":"Nov 16th, 2017","publishedDiff":"4 years ago","whenAvailableForHumans":"4 years">,»length»:93,»lengthForHumans»:»1:33″,»isNew»:false,»isScheduled»:false,»path»:»\/episodes\/1205″,»taxonomy»:<"name":"Tooling","path":"https:\/\/laracasts.com\/browse\/tooling">,»series»:<"title":"Visual Studio Code for PHP Developers","taxonomy":<"name":"Tooling","path":"https:\/\/laracasts.com\/browse\/tooling">,»thumbnail»:»https:\/\/laracasts.nyc3.cdn.digitaloceanspaces.com\/series\/thumbnails\/visual-studio-code-for-php-developers.png»,»path»:»\/series\/visual-studio-code-for-php-developers»>,»viewingStatus»:<"scheduled":false,"watchable":true,"requiresReactivation":null,"requiresBillingDetails":false,"isCompleted":null>,»hasTranscript»:false,»vimeoId»:»243189100″>,»nextEpisode»:<"id":1207,"className":"Laracasts\\Video","chapter":1,"type":"episode","title":"Faster Write-offs With Multiple Cursors","body":"
My working php.ini settings for Windows 10: \n
This works without \n
export XDEBUG_CONFIG=»idekey=vscode» \n
But i have to enable \n
xdebug.remote_enable=1\nxdebug.remote_autostart = 1\n \n
I’m frustrated with xDebug, been so for a while. I followed the steps here but I still can’t get it to work within VS Code. First, Brew removed xdebug: you need to use pecl now. I got a php 7.3.9 and a php-fpm 7.1 from brew. \n
Just went through this problem exactly and the last step where Jeffrey adds the export is what fixed the problem. \n
export XDEBUG_CONFIG=»idekey=vscode» \n
My php.ini config: \n
[XDebug]\nzend_extension = «c:\\xampp\\php\\ext\\php_xdebug.dll»\nxdebug.remote_autostart = 1\nxdebug.remote_enable = 1\nxdebug.profiler_enable= 1\nxdebug.profiler_output_dir=»C:\\xampp\\tmp»\nxdebug.idekey=VSCODE\nxdebug.remote_log =»C:\\xampp\\tmp\\xdebug.log»\n \n
It worked for me just one week until I restarted the computer. I wish this could that easy, but it took me pretty much more investigation and now for some reason is not working and I can not figure it out. It was good while it work 🙂 \n»,»strippedBody»:»It worked for me just one week until I restarted the computer. I wish this could that easy, but it took me pretty much more investigation and now for some reason is not working and I can not figure it out. It was good while it work :)\n»,»bodyInMarkdown»:»It worked for me just one week until I restarted the computer. I wish this could that easy, but it took me pretty much more investigation and now for some reason is not working and I can not figure it out. It was good while it work :)»,»path»:»\/comments\/5180″,»relativePublishDate»:»2 years ago»,»edited»:false,»user»:<"id":63448,"username":"lquintana","avatar":"\/\/unavatar.now.sh\/github\/1quintana","experience":<"award_count":"0","level":3,"points":"13,800","pointsUntilNextLevel":"1,200">,»achievements»:[<"id":16,"name":"Ten Thousand Strong","description":"Earned once your experience points hits 10,000.","level":"intermediate","icon":"ten-thousand-strong.svg">],»reported»:null,»staff»:false,»subscribed»:true,»profile»:<"full_name":null,"bio":null,"twitter":"","github":"1quintana","website":"","employment":"","job_title":"","location":"","flag":null,"available_for_hire":0>,»dateSegments»:<"created_diff":"5 years ago">,»settings»:<"show_profile":true>,»links»:<"profile":"https:\/\/laracasts.com\/@lquintana">>,»replies»:[],»likes»:[],»links»:<"like":"\/comments\/5180\/likes">>,<"id":6573,"video_id":1206,"parent_id":null,"body":"
home-brew no longer has an package for Xdebug. This answer on SO solved it for me. https:\/\/stackoverflow.com\/a\/50181214 \n
Basically after installing PHP with brew, you simply need to use pecl to install Xdebug. It actually enables it all for you in the php.ini file as well. \n
pecl install xdebug\n \n»,»strippedBody»:»home-brew no longer has an package for Xdebug. This answer on SO solved it for me. https:\/\/stackoverflow.com\/a\/50181214\nBasically after installing PHP with brew, you simply need to use pecl to install Xdebug. It actually enables it all for you in the php.ini file as well. \npecl install xdebug\n\n»,»bodyInMarkdown»:»home-brew no longer has an package for Xdebug. This answer on SO solved it for me. https:\/\/stackoverflow.com\/a\/50181214\n\nBasically after installing PHP with brew, you simply need to use pecl to install Xdebug. It actually enables it all for you in the php.ini file as well. \n\n«`\npecl install xdebug\n«`»,»path»:»\/comments\/6573″,»relativePublishDate»:»2 years ago»,»edited»:false,»user»:<"id":150323,"username":"joeworkman","avatar":"\/\/www.gravatar.com\/avatar\/4d9214de6709030a0f6ba0f3564f7ab1?s=100&d=https%3A%2F%2Fs3.amazonaws.com%2Flaracasts%2Fimages%2Fforum%2Favatars%2Fdefault-avatar-27.png","experience":<"award_count":"0","level":2,"points":"7,220","pointsUntilNextLevel":"2,780">,»achievements»:[],»reported»:null,»staff»:false,»subscribed»:false,»profile»:<"full_name":null,"bio":null,"twitter":"","github":"","website":"","employment":"","job_title":"Software Engineer","location":"","flag":null,"available_for_hire":0>,»dateSegments»:<"created_diff":"2 years ago">,»settings»:<"show_profile":true>,»links»:<"profile":"https:\/\/laracasts.com\/@joeworkman">>,»replies»:[<"id":14539,"video_id":1206,"parent_id":6573,"body":"
steps to install xdebug on mac \n
; add this to your php.ini file\nzend_extension=»xdebug.so»\nxdebug.mode=debug\nxdebug.start_with_request=yes\n \n
I am getting «PHP Fatal error: Uncaught Error: Class ‘PHPUnit\\Framework\\TestCase’ not found» when launching currently open script using PHPUnit and xdebug in VS Code. I can run the unit tests fine via the terminal and artisan command so it seems like relative files, such as classes, aren’t autoloading when using the VS Code editor. Has anyone else encountered this? Any suggestions? \n
PHP Refactoring
marsl
VSCode PHP Refactoring README
This is the README for the VSCode PHP Refactoring extension.
Features
Extract Method
You can use the Extract Method refactoring in this way: Select the code lines you want to extract to a method. Then use the command ‘PHP: Extract Method’. Enter the new method name. The new method will be created outside the scope of your current method and will be called at your current location.
Rename Local Variable
You can use Rename Local Variable refactoring in this way: Select the variable with or without the dollar sign you want to rename. Then use the command ‘PHP: Rename Local Variable’. Enter the new variable name with or without the dollar sign. Every occurence of the variable in the specific block will be renamed.
Rename Class Property
You can use Rename Class Property refactoring in ths way: Select the class property with or without the dollar sign you want to rename. Then use the command ‘PHP: Rename Class Property’. Enter the new class property name with or without the dollar sign. Every occurence of the class property in the specific class will be renamed. WARNING: Right now only private class properties can be properly renamed. If the class property is public and used in other files and classes this refactoring will not work.
Requirements
Please note. PHP need to be installed on your machine and it should be set in the environment path or in the Visual Studio Code settings.
Release Notes
Added support for PHP 7 and PHP 8.
Added support for Rename Class Property refactoring.
Added support for Rename Local Variable refactoring.
Initial release of the VSCode PHP Refactoring extension with support for Extract Method refactoring.
Support me
If you like this extension for VS Code and want to invite me for a virtual beer or slice of cake, you can make a donation:
photodude/phpcs-vscode
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
This branch is 6 commits ahead of tommcfarlin:master.
Open a pull request to contribute your changes upstream.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
PHP CodeSniffer and Joomla Coding Standards with VS Code
Last Updated 2017-04-29
This guide is meant to provide all of the steps necessary to easily get up and running with PHP CodeSniffer, the Joomla Coding Standard ruleset, and Visual Studio Code.
All of the resources used in this guide are linked at the bottom. This guide is also licensed MIT. If you’d like to contribute, then please feel free to open issues or issue pull requests. I’ll be happy to merge them and also add your username to CONTRIBUTING.
If you’re looking for a corresponding blog post, please see this page.
As always, don’t forget to checkout the CHANGELOG to track everything that’s changed since the initial release of this guide.
1. Verifying PHP
The following steps assume you have PHP installed and globally accessible on your system. You can test this by entering the following command in the terminal:
And you should see something like this:
If you’re looking for how to use a different version of PHP installed elsewhere on your system, this is not the guide for that. If, however, you’re curious as to where the version of PHP you’re using is stored, you can enter:
And you should see something similar to this:
That should give you enough information for the rest of this guide.
2. Installing Composer
Installing Composer globally means that you’ll be able to access it from anywhere on your system (that is, in any directory regardless of where you are). To do this, you can read the manual or follow the quick steps below (which summarize the manual, anyway):
And now you can access Composer from anywhere in your system. To do try it out, enter the following command in your terminal:
You should see something like this:
With Composer globally installed, you can now install the Joomla Coding Standards rules.
3. Installing PHP CodeSniffer
For the purposes of this document, we’re installing PHP CodeSniffer on a project-by-project basis. To do this, we’re going to be using Composer.
From the integrated terminal within Visual Studio Code, enter the following command:
4. Installing the Joomla Coding Standards Rules
I recommend placing the rules in a directory you can refer to often. Personally, I use a projects directory in my Dropbox directory to manage all of my work because it obviously provides backups automatically (and no, I don’t recommend storing secure files there).
This will create a coding-standards directory in your projects directory and it makes it esay to tell each project where the Joomla Coding Standards are stored because, remember, we’ll be using Composer on a project-by-project basis.
5. Tell PHPCS About The Joomla Coding Standards
From within Visual Studio’s integrated terminal, make sure that you’re in your project’s directory and then issue the following command:
And this will tell your project’s copy of PHPCS where the Joomla Coding Standards are.
6. Update User Settings
Make sure the file looks like the following (though you may need to tweak based on your existing settings)
And this will enable PHPCS and will also tell it to use the standard Joomla ruleset. If this doesn’t start working on the code your have automatically, then restart Visual Studio Code.
About
How to install PHP CodeSniffer and the Joomla Coding Standard Rules in Visual Studio Code.
How to debug PHP using Visual Studio Code
In this tutorial I’m going to teach you how to debug PHP using VS Code Debugger with simple steps.
1. PHP Debug extension
First of all we need to know we have to install an extension to be able to activate the PHP debugger in VS Code. The recommended extension is called PHP Debug. Something we need to notice is that this extension needs Xdebug to work.
2. Xdebug Installation
Xdebug is a PHP extension which provides debugging and profiling capabilities. It uses the DBGp debugging protocol. At this end this tool is responsible to enable the debugging on PHP, and Xcode takes advantage of it.
The debug information that Xdebug can provide includes the following:
Xdebug also provides:
Once we install the extension in Visual Studio Code let’s configure Xdebug. Basically, we need to enable Xdebug in our computer to be capable of creating a new debugging profile in VS Code and can handle the debugging options when we want to debug our code.
And add the following line in the php.ini file:
Download the file and copy it to your PHP installation folder to the
3. Debugging configuration in VS Code
Now we have Xdebug configured, we need to finish the setup in VS Code.
Summary
As you can see to activate the debugging feature for PHP is not as easy as install the extension, but I think the steps are really easy to follow. Please comment me if you were able to configure Xdebug to work with VS Code correctly, or if I missed an extra step to complete the setup.
And finally, thanks for reading my first post 😊. I would be gladded to hear your feedback and suggestions to improve my next post.
felixfbecker/vscode-php-intellisense
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Advanced PHP IntelliSense for Visual Studio Code.
Note: This is just the VS Code extension that spawns the actual language server. The language server itself is implemented purely in PHP in its own repository, all features need to be implemented there and all issues should be reported there. You do NOT need to install it manually though, it is bundled in this extension.
You need at least PHP 7 installed for the extension to work. You can either add it to your PATH or set the php.executablePath setting.
I recommend to disable VS Code’s built-in PHP IntelliSense by setting php.suggest.basic to false to avoid duplicate suggestions.
Workspace symbol search
Find all References
Go to Definition
Find all symbols
Column-accurate error reporting
Code style linting
Please use a dedicated extension like PHP CodeSniffer.
Please use a dedicated extension like PHP CS Fixer.
Clone whole repository and in root directory execute:
The last command will open the folder in VS Code. Hit F5 to launch an Extension Development Host with the extension. For working on the language server, the easiest way is to replace the language server installation from composer in vendor/felixfbecker/language-server with a symlink to your local clone.
For guidance on how to work on the language server, please see the language server repository.
About
Advanced PHP IntelliSense for Visual Studio Code 🆚 💬
15 extensions of VS Code for PHP developer + one for opencart developer
In this post, we are going through the 15 Visual Studio Code extensions that we as PHP developers are using most for the rapid development and collaborations, likewise, show you how to use the Opencart code snippets for rapid development of the Opencart module and themes.
PHP Language Basics
In the extension, search for “@builtin PHP” and enable the “PHP Language Basics” extension. This is the VS Code built-in extension.
PHP Intelephense
Intelephense is a high-performance PHP language server packed full of essential features for productive PHP development.
To avoid double suggestions better to disable the VS code’s built-in PHP Intellisense by setting:
Or in the extension search for “@builtin PHP” and disable the “PHP Language Features” extension.
PHP Debug
Once you configured the Xdebug for your PHP server then you can just add the configuration for the PHP.
The launch.json will look like below:
While debugging, first click the debug button in VS Code, add the breakpoints, you will see lists of breakpoints in the bottom of the left column then enter the URL in your browser then you will see the call stack and variables in the left column. You can move into different steps using the navigation buttons and perform the debug and you can stop by clicking the stop button.
Auto Rename Tag
Auto rename paired tag for HTML, XML, twig, etc. Once you install the extension you need to paste the following setting in the setting.json
The language extension id should be as defined in VS Code extension, for eg: for “.js” file, it will be “javascript”
AutoClose Tag
Automatically add a closing tag when you type in the closing bracket of the opening tag.
Bracket Pair Colorizer 2
An extension that colorizes matching brackets. Use “Bracket Pair Colorizer 2” then V1 “Bracket Pair Colorizer” as it increases the speed and accuracy.
Format HTML in PHP
We can format HTML code in PHP files with this extension, install it and right-click and click “Format HTML in PHP”
Prettier
The Prettier VS Code extension is for code formatting.
MySQL
After installing this extension you can easily run queries and test your queries directly from VS Code. Right-click the database and click “New Query” then type your query, right-click and run the query, which will show the results in the side.
Gitlens
Git in VS code. Install it, connect to GitHub or bitbucket or Git and you can directly push code from the VS code.
Editor Config
PHP Getters & Setters
Create PHP getters and setters from class properties.
PHP Awesome Snippets
A full set of snippets for PHP devs to boost coding productivity.
PHP DocBlocker
This extension is for the documentation. A simple, dependency-free PHP specific DocBlocking package.
https://marketplace.visualstudio.com/items?itemName=neilbrayfield.php-docblocker
Live Share
You can share your Visual studio code with others and get real-time collaborative development within VS Code.
https://marketplace.visualstudio.com/items?itemName=MS-vsliveshare.vsliveshare
Opencart Snippets
For Opencart, we have created the Opencart Snippets which has a collection of OpenCart snippets. Just start with “oc” and it lists out the snippets. Documentation at https://webocreation.com/opencart-code-snippets-vscode-extensions/
The settings.json that we use for our development is as follow:
Please let us know if you have any suggestions, you can also find us on Twitter and Facebook. Enjoy!
О том, как я перешел с PhpStorm на VS Code
В этой статье я не собираюсь делать обзор между VS Code и каким-то редактором или IDE. Я хочу поделиться своим опытом перехода с PhpStorm на Visual Studio Code, работая с проектами, в которых используется typescript, js, node.js и php.
Предисловие
Конечно есть еще целый список must have фич, без которых я бы не обошелся:
Есть еще множество мелочей, которые всем привычны и на них не стоит акцентировать внимание.
Все это прекрасно умеет делать PhpStorm, его индексация файлов позволяет IDE знать ваш же код лучше вас самих. Все прекрасно, кроме скорости. Именно поэтому меня тянуло постоянно попробовать что-то другое. И вот я познакомился с VS Code.
Первый запуск VS Code
Скачав и установив я был очень приятно удивлен скоростью запуска. Конечно не нативный Sublime, но все равно, запуск и открытие папки проекта можно назвать приятным! Без всяких индексаций или загрузки модулей.
При запуске изначально выводится сразу приветственное окно, его можно отключить галочкой в самом окне, либо в настройках:
Кстати, в конце статьи я размещу свой полный конфиг.
Внешний вид
Стандартная тема Dark+ меня полностью устраивает, только включил иконки Seti и убрал с левого бара кнопку плагинов.
Я уменьшил стандартный размер шрифтов до 13, а zoom level установил равным нулю.
Список лучших плагинов для VS Code
VS Code — это, в первую очередь редактор, но после установки необходимых плагинов для front-end разработки, его функционал приблизится к IDE. Бесплатной IDE!
Project Manager
Изначально редактор не поддерживает работу с проектами. В него можно просто скинуть папку и работать с ней. Повторно ее открыть можно из последних открытых файлов или заново перенести папку из finder.
Данный плагин полностью добавляет весь требуемый функционал:
Переключаться между проектами можно с помощью комбинации cmd+option+p.
Beautify
VS Code умеет форматировать html,js,css. Но лишь стандартными настройками и не понимает sass. Данный плагин позволяет настроить форматирование так, как удобно вам и вашей команде. Для себя я настроил так же, как и в PhpStorm для корректной работы с тиммейтами.
Конфиг будет прикреплен внизу статьи.
Форматирование php с помощью Php cs fixer
Пожалуй самая сложная часть с которой мне пришлось заморочиться — это довести до ума форматирование php файлов с html кодом. Перепробовав множество плагинов, даже попытавшись форматировать php с помощью Beautify, я пришел к выводу, что лучшим на данный момент решением будет форматировать с помощью Php cs fixer. Он использует стороннюю библиотеку, которую можно либо установить менеджером пакетов в систему, либо, скачав нужный файлик (php-cs-fixer.phar), указать к нему путь в настройках.
Я предпочел скачать файлик, не устанавливая чего-то лишнего. Загрузить его можно с GitHub.
Установив плагин и указав в настройках путь к файлу, php файлы можно будет форматировать стандартной комбинацией клавиш форматирования.
Скажу честно, добиться такого же результата, как в PhpStrom у меня так и не удалось. Основная проблема осталась с форматированием текстовых тегов (a, span, strong и т.д.), видимо по умолчанию в конфиге php-cs-fixer.phar стоит игнорировать эти теги, как и в Beautify. Если вы работаете с php и знаете лучше способ форматирования кода — милости прошу в комментарии.
Better Merge
В VS Code очень неплохо реализована работа с гитом. По большей части работа сводится к написанию текста коммита и нажатию одной единственной кнопки синхронизации.
Но для облегчения мерджа при конфликтах я использую better merge. В большинстве ситуаций с ним не придется использовать сторонние утилиты.
highlight-matching-tag
Этот небольшой плагин, корректно и симпатично подсвечивает закрывающие html теги даже в php файлах. Стилизацию выделения можно настроить, если стандартная стилизация не понравится.
Auto Rename Tag
Приятный и значительно увеличивающий производительность плагин, который при изменении открывающего / закрывающего тега, автоматически обновляет закрывающий / открывающий тег. Есть возможность настроить список расширений файлов, в которых плагин будет работать.
VS Code обладает неплохим рефакторингом, по крайней мере в TypeScript при переименовании класса или метода, имена переменных обновятся во всех файлах, где импортируется изменяемый класс.
Кстати о импорте: пути к файлам из коробки нужно писать руками. Улучшить ситуацию можно с помощью плагина Path Intellisense.
Path Intellisense
Маленький плагин, который отслеживает ввод «/» и предлагает навигацию по папкам и файлам относительно открытого файла. После указания корректного пути к импортируемому компоненту, VS Code предлагает выбрать классы, которые можно импортировать по введенному пути.
Линтеры
В маркете плагинов для VS Code есть множество линтеров на любой вкус и цвет. Я себе поставил два: ESLint и TSLint. Для работы ESLint необходимо дополнительно установить глобально npm пакет:
Уведомления о замечаниях или ошибках выглядят очень неплохо. Есть подчеркивания прям в коде, а также есть список всех предупреждений, с которым можно ознакомиться в консоли предупреждений. Есть консольная команда автокоррекции и опция автокоррекции, например при сохранении файла.
Установив вышеперечисленные плагины уже можно полноценно работать с проектами и не ощущать дискомфорта. Теперь добавим всевозможных помощников для улучшения нашей производительности.
Сниппеты и улучшения для IntelliSense
Продукты для разработки ПО от Microsoft обладают фирменным инструментом автозавершения кода — IntelliSense, который по какой-то причине из коробки совершенно не поддерживает sass. Поэтому в первую очередь я поставил SCSS IntelliSense.
SCSS IntelliSense
Установив его, редактор прекрасно будет предлагать дописать название стиля или параметра по первым буквам. Но как по мне, такой функционал должен быть из коробки.
Angular v4 TypeScript Snippets
Большой набор сниппетов Angular 4. Введя «a-» + первые буквы желаемого сниппета, IntelliSense предложит вставить готовый кусок кода. Плагин содержит сниппеты как для html шаблонов, так и шаблоны компонентов, директив, модулей и т.д.
HTML CSS Support
Плагин, который добавит подсказки при написании css свойств в html документе.
Проблемные, но уже набравшие популярность плагины
В топе плагинов висит HTML Snippets с 700к+ установками. Но редактор давно поддерживает zen codding, который полностью выполняет суть плагина.
Такая же история с плагином Auto Close Tag, у которого уже почти 300к установок. Но с установленным данным плагином у меня временами зависает UI при работе с Angular 4 проектами. К тому же VS Code из коробки имеет zen codding и может закрывать тег при вводе «
Источники:
- http://habr.com/ru/post/310708/
- http://habr.com/ru/company/microsoft/blog/279947/
- http://marketplace.visualstudio.com/items?itemName=xdebug.php-debug
- http://www.8host.com/blog/nastrojka-visual-studio-code-dlya-razrabotki-php/
- http://marketplace.visualstudio.com/items?itemName=DEVSENSE.phptools-vscode
- http://vscode-eastus.azurewebsites.net/docs/languages/php
- http://blog.theodo.com/2019/07/vscode-php-development/
- http://codinglatte.com/posts/php/visual-studio-code-top-5-extensions-php/
- http://marketplace.visualstudio.com/items?itemName=bmewburn.vscode-intelephense-client
- http://blog.devsense.com/2020/php-8-visual-studio-code
- http://blog.devsense.com/2019/how-to-install-phptools-for-vscode-on-windows
- http://stackoverflow.com/questions/29960999/how-to-run-or-debug-php-on-visual-studio-code-vscode
- http://www.forevolve.com/en/articles/2016/08/04/php-with-visual-studio-code-and-xdebug/
- http://github.com/xdebug/vscode-php-debug
- http://appdividend.com/2018/10/31/how-to-use-php-in-visual-studio-code/
- http://techvideostack.com/php-in-visual-studio-code-your-first-php-project/
- http://marketplace.visualstudio.com/items?itemName=ikappas.phpcs
- http://waleev.ru/vs-code-extensions-for-php/
- http://marketplace.visualstudio.com/items?itemName=jasonterando.vscode-php-tdd
- http://github.com/brapifra/vscode-phpserver
- http://byurrer.ru/vs-code-kak-ide-dlya-php.html
- http://www.codewall.co.uk/best-visual-studio-code-php-extensions/
- http://marketplace.visualstudio.com/items?itemName=obliviousharmony.vscode-php-codesniffer
- http://marketplace.visualstudio.com/items?itemName=shevaua.phpcs
- http://marketplace.visualstudio.com/items?itemName=kokororin.vscode-phpfmt
- http://marketplace.visualstudio.com/items?itemName=ValeryanM.vscode-phpsab
- http://stackoverflow.com/questions/10529214/how-to-use-php-with-visual-studio
- http://marketplace.visualstudio.com/items?itemName=ikappas.composer
- http://stackoverflow.com/questions/68639575/how-to-change-the-version-of-php-in-vscode
- http://github.com/ikappas/vscode-phpcs
- http://github.com/kolei/vsc_xdebug
- http://de-vraag.com/ru/61048090
- http://techvideostack.com/php-in-visual-studio-code-setup-debugging/
- http://docs.joomla.org/Visual_Studio_Code
- http://docs.devsense.com/
- http://habr.com/en/post/310708/?mobile=no
- http://dev.to/ryan1/the-best-setting-json-for-php-development-with-visual-studio-code-4agc
- http://laracasts.com/series/visual-studio-code-for-php-developers/episodes/11
- http://www.pvsm.ru/php-2/115858
- http://dev.to/sainathpoojary/how-to-run-php-in-visual-studio-code-in-2021-hec
- http://alexanderallen.medium.com/visual-studio-code-wsl-running-php-intellisense-from-alpine-linux-on-windows-10-78e8a990f1cc
- http://marketplace.visualstudio.com/items?itemName=rifi2k.format-html-in-php
- http://stackoverflow.com/questions/40287927/php-executable-not-found-install-php-7-and-add-it-to-your-path-or-set-the-php-e
- http://nastoysam.ru/internet/nastrojka-redaktora-visual-studio-code-dlya-razrabotki-na-php
- http://dev.to/wildtuna/visual-studio-code-kak-altiernativa-phpstorm-dlia-backend-razrabotchika-1d7k
- http://qna.habr.com/q/841127
- http://github.com/tommcfarlin/phpcs-wpcs-vscode
- http://vscode-docs.readthedocs.io/en/latest/languages/php/
- http://marketplace.visualstudio.com/items?itemName=neilbrayfield.php-docblocker
- http://www.codewall.co.uk/how-to-run-php-code-directly-in-the-visual-studio-code-console-terminal/
- http://marketplace.visualstudio.com/items?itemName=JillMNolan.php-development-essentials
- http://docs.devsense.com/en/vscode/debug
- http://stackoverflow.com/questions/47748392/php-coding-standards-visual-studio-code
- http://phptime.ru/questions/29960999/how-to-run-or-debug-php-on-visual-studio-code-vscode/
- http://github.com/wongjn/vscode-php-sniffer
- http://github.com/INsReady/docker-vscode-php
- http://stackoverflow.com/questions/43055889/using-php-and-mysql-in-vs-code
- http://marketplace.visualstudio.com/items?itemName=persoderlind.vscode-phpcbf
- http://stackoverflow.com/questions/41330707/how-can-i-format-php-files-with-html-markup-in-visual-studio-code
- http://laracasts.com/series/visual-studio-code-for-php-developers/episodes/13
- http://marketplace.visualstudio.com/items?itemName=marsl.vscode-php-refactoring
- http://github.com/photodude/phpcs-vscode
- http://dev.to/vidamrr/how-to-debug-php-using-visual-studio-code-1gna
- http://github.com/felixfbecker/vscode-php-intellisense
- http://webocreation.com/15-extensions-of-vs-code-for-php-developer-one-for-opencart-developer/
- http://golosay.net/from-phpstorm-to-vs-code/