Symfony Phpstorm



Published on 2020-06-21 • Modified on 2020-10-18

1 Open PHPStorm, click on the Settings/Preferences menu, select the Plugins option and click on the Browse repositories button: 2 Select SymfonyInsight plugin from the list and click on the Install plugin button. 3 Restart PHPStorm for the changes to take effect. SymfonyInsight plugin configuration ¶. Enabled Symfony Plugin per project (File Settings Symfony Plugin) Install Php Annotation plugin to enjoy all the annotation stuff Plugin needs a valid PhpStorm indexer, use 'File Invalidate Caches / Restart' if something crazy is going on.

In this post, we will see how to do step by step debugging with Xdebug, Symfony and PHPStorm. We will do a basic example where we will stop the execution of the Symfony code just before rendering a template to check the data passed to it. Let's go! 😎

  • Lean and Mean Dev with PhpStorm (for Symfony) Download. Course Code This Video Course Script Chapter 02. Annotations 2:47.
  • I would recommend using Visual Studio Code or PhpStorm. The former is free, the latter is not but has a better integration with Symfony (thanks to the Symfony Support Plugin). It is up to you. I know you want to know which IDE I am using. I am writing this book in Visual Studio Code.
  • PhpStorm provides coding assistance and navigation facilities for developing applications with the Symfony framework. Symfony support is provided by means of the Symfony Plugin. The source code for the plugin, as well as its issue tracker, can be found on GitHub.

» Published in 'A week of Symfony 704' (22-28 June 2020).

Prerequisite

I will assume you have a basic knowledge of PHP, Symfony and that you know how to modify your PHP configuration thanks to the php.ini file.

Introduction

Why this blog post? Well, because of this tweet:

PHP developers that don't use Xdebug for debugging are amateurs.

— Derick Rethans 🔶 (@derickr) June 20, 2020

This is the kind of tweet I don't like, a typical troll, trying to make a generality of something more complex. It brings negativity as It can be interpreted by people not using Xdebug by:

“If you don't use Xdebug, you aren't a real developer.” 😔

Even it's not what Derick meant to say, it's what people may understand. There is no smiley. We don't know if the tweet is pure sarcasm or not. I wanted to answer at first. But what about transforming something negative to something positive and useful? 😀 That's why I decided to write this blog post. 🙂

Configuration

I use the following configuration, but it should be OK with previous versions of each of these components. Here, I use the Symfony binary to serve my application. If you use another type of setup (Apache, Docker...), you'll probably have to make small adjustments to the following instructions.

  • PHP 7.4
  • Symfony 5.2
  • Xdebug 2.9.6
  • PHPStorm 2020.3

Installation

I will assume you have a working PHP/Symfony installation. So first let's install Xdebug, it can be done with PECL:

If not done, activate the Xdebug extension in your php.ini file. You can find this file by running:

Verify that in this file, the xdebug.so (or .dll) library is loaded. You must see a line like the following (it can also be loaded in an external file like conf.d/ext-xdebug.ini):

If everything is OK, you should now see Xdebug when getting the PHP version:

Or when grepping the module list:

The debug bar also shows if Xdebug is available when you pass over the Symfony version number with your mouse:


Now that Xdebug is activated let's see how to configure it for PHPStorm.

Configuring Xdebug and PHPStorm

Xdebug

First, we must enable the remote option of Xdebug. Add the following parameter in your PHP configuration as we did previously:

We keep the other default parameters to keep the configuration as minimal as possible. So, with this setup, the port used by Xdebug is 9000 and the default IP address is 127.0.0.1. Check out the xdebug.remote_host and xdebug.remote_port parameters in the documentation.

PHPStorm

Now, let's check the configuration inside PHPStorm. Open the menu entry: Run > Web Server Debug Validation. You should see this window:


In the first parameter put the full path of your project public directory where is stored the Symfony front controller (generally public/index.php with Symfony 5). In the second parameter, put the local URL of your project. Then click on validate. If everything is OK, you should see ✅ like above. You can ignore the error of the last line, it seems to be a known problem, but it won't prevent the debugger from working. The final step is to tell PHPStorm to start listening to Xdebug connections. It must be done with the Run > Start Listening for PHP Debug connections menu entry.

Step by step debugging

Now that PHPStorm has validated our setup let's try to add our first breakpoint. Open one of your controllers and click between the line number and the start of the code editor panel of the line you want to stop the execution. A red disc 🔴 appears like this (at line 33 in this example):


Now, open your browser and access a page that calls the action where we put the breakpoint. If it works, PHPStorm gets back as the active window of your OS, and you get the following output:


As you can see, the code window is different from what we use to have. First, after the controller method declaration line, we have the values of the parameters received by the action. $_locale is 'en', $goals is an array with two keys, and lastly, $articleRepository is the Doctrine repository of the Article entity. Just below, we see that the line of the breakpoint is highlighted; this is to show that the code has stopped here like expected. Just before this line, after the declaration of the $data (at the right), we see the value of this new variable. It is empty as we just declared it.
Just below, in the debug panel, we have a Variables section where we can inspect all the local variables available at the breakpoint.


This panel is very convenient; we can see all the variables (even the globals) and expand them to check their content. We also find the function parameters ($_locale, $goals, $articleRepository). As this controller extends the Symfony AbstractController, we can notice that it has access to the dependency injection container ($this->container).

Now let's try to advance to the next 'step', to go to the next line. We can use the 'Step over' button (F6 with my setup).


As you can see the highlighted line has changed, it's now line n°34. We can see the value of the $date variable just above. This new $date variable is now part of the 'Variables' panel. We can continue like this until the end of the action to check that the $data array contains the correct keys and values and can be passed to the Twig template. To continue the execution of the script, click on the 'Resume program' button ⏯️ (F8).
If you don't need the breakpoint for now but want to keep it for later, you can right-click on it and deselect the 'Enabled' option. The red disc appears now as a circle. Refresh the page, and you will notice that the script doesn't stop anymore.

The browser extension

We can also install a browser extension (available for Firefox, Chrome, Safari, Opera) to disable/enable the debug on the fly. When disabled, nothing is caught by PHPStorm even there are still some active breakpoints. It is faster than deactivating the breakpoint manually or altogether disable Xdebug in the PHP configuration. It looks like this:


Conclusion

Et voilà! We have a practical step by step debugging workflow using Xdebug! What about telling Derick that we are now professionals PHP developers? 😁

About the original tweet, I really liked the answer of Jordi; this is precisely what I think:

I can see a debugger being valuable when code is very complex or unknown, and often use it in JS. In PHP code though I usually am familiar enough with what libs I use and find no benefit to debugging interactively. Like most things, it depends. No need to call people amateurs IMO

— Jordi Boggiano (@seldaek) June 20, 2020To see parodic tweets of the original one, click on this link 😜.

If you don't drink Guinness you are an amateur

— Gary Hockin (@GeeH) June 20, 2020

PHP developers who don’t use @doctrineproject are amateurs.

— Jonathan H. Wage (@jwage) June 20, 2020

Developers that don't use a computer to develop are amateurs

Symfony Phpstorm Phpunit

— Gregoire Pineau (@lyrixx) June 21, 2020

PHP developers that don't write there own frameworks are amateurs

— Simon Bennett (@MrSimonBennett) June 20, 2020

PHP developers that write bugs and need to debug are amateurs. https://t.co/NG5YtmdD3k

— Liam Hammett (@LiamHammett) June 20, 2020

That's it! I hope you like it. Check out the links below to have additional information related to the post. As always, feedback, likes and retweets are welcome. (see the box below) See you! COil. 😊

They gave feedback and helped me to fix errors and typos in this article, many thanks to jmsche. 👍

Did you like this post? You can help me back in several ways: (use the Tweet on the right to comment or to contact me )

  • Report any error/typo.
  • Report something that could be improved.
  • Like and retweet!
  • Follow me on Twitter
  • Subscribe to the RSS feed.
  • Click on the More on Stackoverflow buttons to make me win 'Announcer' badges 🏅.

Thank you for reading! And see you soon on Strangebuzz! 😉

[🇬🇧] New blog post, this is my answer to the tweet: 'PHP developers that don't use #Xdebug for debugging are amateurs.' https://t.co/SPd8UIOrQ8 Proofreading, comments, likes and retweets are welcome! 😉Annual goal: 4/6 (66%) #php#strangebuzz#blog#blogging#debug#bug#blogging

— COil #StaySafe 🏡 #OnEstLaTech ✊ (@C0il) June 23, 2020

Introducing CW: a cache watcher for Symfony

Adding a custom data collector in the Symfony debug bar

Before starting to work on the project, we need to check that everyone has agood working environment. It is very important. The developers tools we have atour disposal today are very different from the ones we had 10 years ago. Theyhave evolved a lot, for the better. It would be a shame to not leverage them.Good tools can get you a long way.

Please, don’t skip this step. Or at least, read the last section about theSymfony CLI.

A Computer¶

You need a computer. The good news is that it can run on any popular OS: macOS,Windows, or Linux. Symfony and all the tools we are going to use are compatiblewith each of these.

Opinionated Choices¶

I want to move fast with the best options out there. I made opinionated choicesfor this book.

PostgreSQL is going to be our choice for everything: from database toqueues, from cache to session storage. For most projects, PostgreSQL is thebest solution, scale well, and allows to simplify the infrastructure with onlyone service to manage.

At the end of the book, we will learn how to use RabbitMQ for queues andRedis for sessions.

IDE¶

You can use Notepad if you want to. I would not recommend it though.

I used to work with Textmate. Not anymore. The comfort of using a “real” IDE ispriceless. Auto-completion, use statements added and sorted automatically,jumping from one file to another are a few features that will boost yourproductivity.

I would recommend using Visual Studio Code or PhpStorm. The formeris free, the latter is not but has a better integration with Symfony (thanks tothe Symfony Support Plugin). It is up to you. I know you want to know whichIDE I am using. I am writing this book in Visual Studio Code.

Terminal¶

We will switch from the IDE to the command line all the time. You can use yourIDE’s built-in terminal, but I prefer to use a real one to have more space.

Linux comes built-in with Terminal. Use iTerm2 on macOS. On Windows,Hyper works well.

Symfony

Git¶

My last book recommended Subversion for version control. It looks likeeverybody is using Git now.

On Windows, install Git bash.

Phpstorm

Be sure you know how to do the common operations like running gitclone,gitlog, gitshow, gitdiff, gitcheckout, …

PHP¶

We will use Docker for services, but I like to have PHP installed on my localcomputer for performance, stability, and simplicity reasons. Call me old schoolif you like, but the combination of a local PHP and Docker services is theperfect combo for me.

Use PHP 8.0 and check that the following PHP extensions are installed or install them now: intl, pdo_pgsql,xsl, amqp, gd, openssl, sodium. Optionallyinstall redis, curl, and zip as well.

You can check the extensions currently enabled via php-m.

We also need php-fpm if your platform supports it, php-cgi works aswell.

Composer¶

Managing dependencies is everything nowadays with a Symfony project. Get thelatest version of Composer, the package management tool for PHP.

If you are not familiar with Composer, take some time to read about it.

Tip

You don’t need to type the full command names: composerreq does thesame as composerrequire, use composerrem instead of composerremove, …

NodeJS¶

We won’t write much JavaScript code, but we will use JavaScript/NodeJS tools tomanage our assets. Check that you have the NodeJS installed and the Yarnpackage manager.

Docker and Docker Compose¶

Services are going to be managed by Docker and Docker Compose. Install themand start Docker. If you are a first time user, get familiar with the tool.Don’t panic though, our usage will be very straightforward. No fancyconfigurations, no complex setup.

Symfony Phpstorm

Symfony CLI¶

Last, but not least, we will use the symfony CLI to boost our productivity.From the local web server it provides, to full Docker integration andSymfonyCloud support, it will be a great time saver.

Phpstorm Symfony Missing Asset

Plugin

Install the Symfony CLI and move it under your $PATH. Create aSymfonyConnect account if you don’t have one already and log in viasymfonylogin.

To use HTTPS locally, we also need to install a certificate authority (CA)to enable TLS support. Run the following command:

Check that your computer has all needed requirements by running the followingcommand:

If you want to get fancy, you can also run the Symfony proxy. It is optionalbut it allows you to get a local domain name ending with .wip for yourproject.

Log

When executing a command in a terminal, we will almost always prefix it withsymfony like in symfonycomposer instead of just composer, orsymfonyconsole instead of ./bin/console.

The main reason is that the Symfony CLI automatically sets some environmentvariables based on the services running on your machine via Docker. Theseenvironment variables are available for HTTP requests because thelocal web server injects them automatically. So, using symfony on the CLIensures that you have the same behavior across the board.

Moreover, the Symfony CLI automatically selects the “best” possible PHP versionfor the project.