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
PHP Intelephense can also auto-suggest relevant methods when typing $myVar-> . The problem is that these suggestions are polluted by the default PHP suggestions.
Basic PHP code suggestions we want to disable
To fix that, you can disable these basic suggestions in VS Code settings. Simply open VS Code’s settings.json file (press Ctrl + , then click on the top right <> icon) and add the following line:
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):
Check that Xdebug is successfully installed by running php -v . You should get something like:
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:
- adding or removing breakpoints
- stepping over, into or out
- watching variables
- evaluating expressions in the debug console
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
If you want to disable or enable some specific linting rules, you can do it in a .php_cs file at the root folder of your project. If this configuration file is present, VS Code takes it into account and overrides the configuration found in settings.json . You can find more information about the .php_cs file in the GitHub repository. A simple config file to use @PhpCsFixer category and disable some rules could be:
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.
Top 10 Best VS Code Extensions for PHP Developers
In this article, we’ll put together a curated list of the top 10 VS Code extensions for PHP developers that you can add to your toolbox to improve your productivity and make you more efficient when writing PHP code.
Over the years, Visual Studio Code has become one of the most popular IDEs in the developer market. It was ranked the most popular Integrated Development Environment in the Stack Overflow 2022 Developer Survey, with 74.48% of the respondent using it as their primary editor. It aims to offer all the tools a developer needs while cutting out the robust features of full IDEs.
PHP is one of the top programming languages used by developers worldwide for creating a variety of dynamic and interactive websites. But VS Code does not support PHP out-of-the-box. Therefore, if you want to develop PHP applications in VS Code, it is important to install extensions that empower VS Code to support PHP.
1 – PHP Intelephense
PHP Intelephense is a popular PHP extension for VS Code that provides advanced features for productive PHP development. Some of the essential features of this extension include code auto-formatting, rich information tooltips on mouse hover, enhanced navigation between components, fast camel/underscore case code completion, and real-time error diagnostics for open files via powerful static code analysis.
Other features include:
- Smart highlight for keywords and references.
- Full document and workspace symbol search
- Detailed signature help for documents, methods, functions, workspace, and built-in constructors.
- Detailed hover with links to official PHP documentation.
2 – PHP Tools
There are two PHP extensions in VS Code – PHP Tools and PHP Intelephense but PHP Tools provide a bunch of useful tools for the PHP language. The extension empowers VS Code with fast code completion, code formatting, code lenses, code fixes, test explorer, tests debugger, code generators, debugger, built-in development web server, and code analysis.
Among all these features, my favourite is the code lens feature which enables me to immediately see how many times functions, classes, and properties are used. By clicking on a code lens, a popup will be displayed where you click on the class, function, or property declaration to see the actual definition.
Should you choose PHP Tools over PHP Intelephense? PHP Intelephense is a freemium extension and it has a couple of useful features inside the free version.
PHP Tools on the other hand has similar features to PHP Intelephense but it has great features that are not present in PHP Intelephense like integrated generic support, built-in debugging and unit testing support, the possibility to search todos inside the whole workspace, and a few others.
My honest recommendation is: try both and choose the one that suits your needs. One thing to note is PHP Tools has annual subscriptions whereas PHP Intelephense has a lifetime subscription.
3 – Composer
When you install PHP Tools, it also installs Composer and PHP Profiler extensions by default. However, if you decide to go with PHP Intelephense then you need to install the Composer extension separately.
Composer is an “All-in-One” extension that provides complete integration of composer and packagist in Visual Studio Code. The extension provides quick composer commands, code actions, schema validation, code lenses, IntelliSense for composer.json, browse and search packages, and it extends VS Code with composer tasks.
4 – PHP Awesome Snippets
One of the things most PHP developers struggle with is typing Class blocks, function signatures, or other common PHP statements over and over again. Therefore, the PHP Awesome Snippets VS Code plugin was developed to provide snippets for common patterns in PHP. These snippets are based on or follow the PSR-1, PSR-2, and PSR-12 coding standards provided by PHP-FIG.
Assuming you want to implement some logic with an if/else statement, you can type “ifel” and IntelliSense will kick in to display all the snippets that match the symbol.
Then, you can use the up/down arrow keys to move between the options and click on the snippet you want to generate the code from.
Note: The snippets are meant to work in PHP files and tags. However, they are also available in plain text context for convenience.
5 – Code Runner
Code Runner is a VS Code extension that allows developers to run code snippets or code files for different programming languages. This plugin can execute code snippets written in languages like C, C++, Java, JavaScript, PHP, Python, Perl, Perl 6, Ruby, Go, Lua, Groovy, PowerShell, BAT/CMD, BASH/SH, F# Script, F# (.NET Core), C# Script, C# (.NET Core), VBScript, TypeScript, CoffeeScript, Scala, Swift, Julia, etc.
Some of its features include:
- Run selected piece of code
- Run a code file through the context menu of the file explorer
- Stop a running code
- Set default programming language
To run a piece of code, select the block of code and right-click on the selected code to display the editor context menu. After that, click on the “Run Code” button in the context menu to execute the code.
6 – Docker
The Docker VS Code extension makes it easy to build, manage, and deploy containerized applications directly in Visual Studio Code. It provides IntelliSense, auto-completions, and syntax for common commands when editing Dockerfile and docker-compose.yml files. In addition, it makes debugging PHP, Node.js, Python, and .NET core applications inside Docker containers a breeze.
Manually writing Docker and Docker-compose files can be tedious and error-prone. Luckily, the Docker VS Code extension has a feature to generate appropriate Docker files for your project.
Apart from that, it also provides a bunch of commands that can be used to spawn Docker containers, manage, and deploy the containers without writing a single line of command in the terminal.
7 – EditorConfig
The EditorConfig plugin attempts to override user/workspace settings with configurations found in .editorconfig files. The extension is activated whenever you open a new text editor, switch tabs into an existing one, or focus on an already opened editor.
When the EditorConfig extension is activated, it uses the editorconfig NPM package to resolve the configuration for that specific file and applies any relevant editor settings.
What is an EditorConfig file? It is a text format file that gives you the possibility to preserve consistency when multiple team members are working on the same project across various editors and IDEs. So you can define coding styles or conventions that text editors and IDEs must adhere to throughout the project’s life cycle.
8 – Code Spell Checker
Code Spell Checker is a lightweight extension built to catch common spelling errors while keeping the number of false positives low. It automatically detects and excludes keywords of various programming languages from spell-checking.
One great feature of Code Spell Checker is it has multi-language support. Some of the languages include Russian, Catalan, Czech, Danish, Dutch, French, French Réforme 90, Polish, Portuguese – Brazilian, Portuguese, and many more.
The extension is automatically enabled for programming languages like PHP, Python, Rust, Scala, Text, TypeScript, YAML, C, C++, C#, CSS, less, sass, Elixir, Go, SON / JSONC, LaTex, Markdown, and more.
Words that are not in the dictionary files will have squiggly underlines. This way, you can easily point out misspelled words and correct them.
9 – RapidAPI Client
Usually, when we build APIs with PHP, we turn to use API testing software like Postman or Insomnia to test the API endpoints. These API testing tools are great for testing complex APIs but RapidAPI Client provides a simple and intuitive interface for testing API endpoints directly in VS Code.
RapidAPI Client extension is designed to work well with any VS Code theme. It comes with tools for composing API requests, inspecting server responses, generating client code, and exporting API definitions directly from the interface without ever switching to an external application like Postman.
Similar to Postman or Thunder Client VS Code extension, the RapidAPI Client extension can also be used to test GraphQL API endpoints.
10 – MySQL by Weijan Chen
The MySQL by Weijan Chen extension is a powerful GUI for querying and analyzing data stored in a wide variety of servers like MySQL, MariaDB, PostgreSQL, SQL Server, MongoDB, Redis, ElasticSearch, and more. It can also be used as an SSH client.
This extension becomes handy when you want to quickly explore and manipulate your database directly in VS Code. For example, when you are building a PHP application that uses MySQL or PostgreSQL or any supported database server, you can easily connect and manage the data directly in VS Code without the need for an external application.
This extension supports both NoSQL and SQL databases. Suppose you want to connect to a PostgreSQL database, select the Database tab on the left sidebar and click on the Create Connection button.
Then, select the server type from the supported list and provide the server credentials in the input fields. Alternatively, you can turn on the “Use Connection String” radio button and paste the database connection URL in the “Connection String” input field.
Next, click on the “Connect” button to connect to the database server. Assuming the credentials are valid, the database will be displayed in the left pane.
Now that you’ve successfully connected to the database, you can manage the data directly in the GUI provided by the MySQL extension.
Настройка 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 поставляется с несколькими темами, которые позволяют изменять цвета, используемые в интерфейсе редактора и при выделении кода. По умолчанию включены темный и светлый стили.
Перейдите в File -> Preferences -> Color Theme или нажмите CTRL+K+T, чтобы выбрать другую тему для VS Code.
Также можно установить расширения для темы, чтобы дополнительно настроить внешний вид VS Code. Если вы выполните поиск (CTRL + SHIFT + X), вы найдете несколько расширений для темы с разными стилями и цветами, включая цветовые схемы, перенесенные из других популярных редакторов и платформ.
Настройка шрифта
В целом, настройки шрифтов VS Code по умолчанию достаточно хороши – многие пользователи предпочитают не менять их. Но если вы хотите, вы можете настроить размер и тип шрифта редактора для повышения удобочитаемости.
Если вам нужно изменить размер шрифта или выбрать другой тип, вы можете перейти в меню File -> Preferences -> Settings, а затем выбрать Text Editor в левом меню. В открывшемся подменю нажмите Font. Этот раздел содержит настройки семейств и размеров шрифтов, которые вы можете выбрать по своему усмотрению.
Изменения немедленно сохраняются и применяются ко всем текущим открытым файлам.
Заключение
Visual Studio Code – это легкий, но мощный редактор кода, который можно настроить в соответствии с потребностями большинства разработчиков. В этом руководстве вы узнали, как установить и настроить расширение PHP Intelephense для работы над проектами PHP, как импортировать и создавать новые проекты в VS Code и как настроить внешний вид редактора, чтобы сделать процесс разработки более удобным.
Visual Studio Code как альтернатива PHPStorm для Backend-разработчика
В сложившейся ситуации с покупкой продуктов JetBrains на территории РФ задумался об альтернативе одному из их продуктов PHPStorm. Давно слышал много хороших отзывов о VSCode и решил попробовать поработать в нем недельку. Начал с изучения доступных расширений и их настройки. В итоге мне удалось собрать под себя очень достойную альтернативу PHPStorm. В чем-то она хуже, в чем то лучше продукта от JetBrains, но для себя я решил пока остаться на VSCode. Ниже я поделюсь с вами расширениями, которые использую и настройками.
Начинаем с установки Visual Studio Code. Для этого нужно скачать установщик с официального сайта. После установки мы получим голый VSCode.
При желании можно установить языковый пакет, который локализует интерфейс приложения.
Установка расширений
Менеджер проектов
По умолчанию в VSCode нет привычной работы с проектами, но эту проблему легко решить используя расширение Project Manager. Чтобы создать проект открываем папку с файлами, которую хотим использовать как проект, нажимаем ctrl+shift+P, в появившейся строке вводит Project и выбираем выделенный ниже элемент списка.
Будет предложено ввести имя проекта.
После подтверждения проект будет создан и его можно будет увидеть в разделе с проектами.
При клике на проект VSCode сразу откроет папку, к которой был привязан проект.
Расширения для PHP
Для комфортной работы с PHP необходимо установить эти расширения:
- Для отладки через XDebug
- Для удобной работы с кодом PHP Intelephense (Очень советую приобрести Premium версию)
- Альтернатива предыдущего расширения для работы с кодом PHP IntelliSense (На мой взгляд хуже предыдущего)
- Для работы с DocBlock PHP DocBlocker
- Для автовставки Namespace PHP Namespace Resolver
- Для генерации getters и setters
- Генератор конструктора PHP Constructor
- Добавляет генерацию классов, интерфейсов, трейтов, enum при создании нового файла PHP Create Class
- Вставка подсказок type hints и входных параметров PHP Parameter Hint
- Для работы с Composer
- Для подсказок пакетов и версий в composer.json Composer IntelliSense
- CSFixer по желанию, требуется установленный на машине PHP
Если включить одновременно IntelliSense и Intelephense, то будут задвоены подсказки методов и аннотации с описанием функций.
После установки расширений нужно отключить базовые подсказки PHP VSCode. Для этого нужно в расширениях в поисковой строке ввести @builtin php и отключить расширение PHP Language Features.
Расширения для Symfony
Расширения для Laravel
Работа с тэгами
Для удобства работы с HTML, XML и прочими документами с тэгами:
Встроенный Rest Client
Rest client по аналогии с тем, что был добавлен в PHPStorm
REST Client.
Thunder Client — встроенный клиент, похожий на Postman.
Работа с проектом по 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
Для форматирования нужно использовать комбинации славишь ниже:
- Ctrl(Cmd)+Alt+M для преобразования JSON в читаемый вид
- Alt+M для минимизализации JSON
Форматирование SQL SQL Formatter
При нажатии правой кнопки мыши по выделенному SQL в меню появится новый блок после установки расширения.
TODO и FIXME
Работая с PHPStorm многие из вас привыкли к удобному просмотру TODO и FIXME в виде списка по всему проекту. В VSCode для этой задачи есть два расширения.
Todo Tree — очень удобное расширение, позволяет видеть все TODO в виде списка, огромные возможности кастомизации отображения, возможность добавлять свои тэги.
TODO Highlight — расширение попроще предыдущего, но также позволяет кастомизировать отображение и добавлять свои тэги. На мой взгляд менее удобно реализован листинг TODO по проекту.
Работа с таск-трекерами
Для быстрой работы с задачами прямо из VSCode для себя использую эти расширения:
- Redmine — позволяет быстро просматривать список задач, менять статусы и трекать затраченное время;
- YouTrack — позволяет смотреть задачи, создавать ветки при открытии задачи, MR и прочее;
- YouTrack Issues — попроще предыдущего, но мне он нравится больше, так как сосредоточен только на работе с задачами и более удобный листинг задач;
- Jira and Bitbucket — официальное расширение, которое отлично реализует работу с задачами в Jira и Bitbucket.
В магазине VSCode есть большой выбор тем. Мне больше всего нравится во всех IDE Twilight Twilight Theme Многим нравится GitHub Theme. В целом в магазине каждый найдет что-то на свой вкус.
Если вы обычно работаете с несколькими окнами VSCode одновременно, то вас может заинтересовать расширение Peacock, которое позволяет задать окнам IDE разную палитру и проще ориентироваться в открытых проектах.
Прочее
Total Lines — добавляет в тулбар информацию, о количестве строк в файле.
Regex Previewer — быстрая отладка регулярных выражений прямо в VSCode.
Bookmarks — для удобных флажков на строчки кода.
Better Comments — кастомизация комментариев в коде.
Edit CSV — просмотр и редактирвоание CSV.
Hungry Delete — быстрое удаление пустых строк и пробелов одним нажатием.
Path Intellisense — автоподставление путей к файлам.
Настройки
Посе установки всех необходимых расширений необходимо произвести некоторые настройки в самом 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
Для работы с задачами в таск-трекере Redmine в конфигурационном файле settings.json в каталоге .vscode проекта нужно добавить настройки ниже. После сохранения для работы нужно перезапустить VSCode.
Exit fullscreen mode
Настройка расширения Intelephense
Чтобы указать версию PHP у проекта для корректной работы линтера нужно в файле settings.json в проекте указать ее, как показано ниже.
Exit fullscreen mode
Спасибо, что дочитали до конца! Надеюсь, моя инструкция будет полезна и вам!