The VarDumper Component

The VarDumper Component

The VarDumper component provides mechanisms for extracting the state out of any PHP variables. Built on top, it provides a better `dump() function that you can use instead of var_dump.

Installation

  1. $ composer require --dev symfony/var-dumper

Note

If you install this component outside of a Symfony application, you must require the vendor/autoload.php file in your code to enable the class autoloading mechanism provided by Composer. Read this article for more details.

Note

If using it inside a Symfony application, make sure that the DebugBundle has been installed (or run composer require --dev symfony/debug-bundle to install it).

The dump() Function

The VarDumper component creates a global `dump() function that you can use instead of e.g. var_dump. By using it, you’ll gain:

  • Per object and resource types specialized view to e.g. filter out Doctrine internals while dumping a single proxy entity, or get more insight on opened files with stream_get_meta_data;
  • Configurable output formats: HTML or colored command line output;
  • Ability to dump internal references, either soft ones (objects or resources) or hard ones (=& on arrays or objects properties). Repeated occurrences of the same object/array/resource won’t appear again and again anymore. Moreover, you’ll be able to inspect the reference structure of your data;
  • Ability to operate in the context of an output buffering handler.

For example:

  1. require __DIR__.'/vendor/autoload.php';
  2. // create a variable, which could be anything!
  3. $someVar = ...;
  4. dump($someVar);
  5. // dump() returns the passed value, so you can dump an object and keep using it
  6. dump($someObject)->someMethod();

By default, the output format and destination are selected based on your current PHP SAPI:

  • On the command line (CLI SAPI), the output is written on STDOUT. This can be surprising to some because this bypasses PHP’s output buffering mechanism;
  • On other SAPIs, dumps are written as HTML in the regular output.

Tip

You can also select the output format explicitly defining the VAR_DUMPER_FORMAT environment variable and setting its value to either html or cli.

Note

If you want to catch the dump output as a string, please read the advanced documentation which contains examples of it. You’ll also learn how to change the format or redirect the output to wherever you want.

Tip

In order to have the `dump() function always available when running any PHP code, you can install it globally on your computer:

  1. Run composer global require symfony/var-dumper;
  2. Add auto_prepend_file = ${HOME}/.composer/vendor/autoload.php to your php.ini file;
  3. From time to time, run composer global update symfony/var-dumper to have the latest bug fixes.

Tip

The VarDumper component also provides a dd() (“dump and die”) helper function. This function dumps the variables usingdump() and immediately ends the execution of the script (using exit).

The Dump Server

The `dump() function outputs its contents in the same browser window or console terminal as your own application. Sometimes mixing the real output with the debug output can be confusing. That’s why this component provides a server to collect all the dumped data.

Start the server with the server:dump command and whenever you call to `dump(), the dumped data won’t be displayed in the output but sent to that server, which outputs it to its own console or to an HTML file:

  1. # displays the dumped data in the console:
  2. $ php bin/console server:dump
  3. [OK] Server listening on tcp://0.0.0.0:9912
  4. # stores the dumped data in a file using the HTML format:
  5. $ php bin/console server:dump --format=html > dump.html

Inside a Symfony application, the output of the dump server is configured with the dump_destination option of the debug package:

  • YAML

    1. # config/packages/debug.yaml
    2. debug:
    3. dump_destination: "tcp://%env(VAR_DUMPER_SERVER)%"
  • XML

    1. <!-- config/packages/debug.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/debug"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:debug="http://symfony.com/schema/dic/debug"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd
    8. http://symfony.com/schema/dic/debug https://symfony.com/schema/dic/debug/debug-1.0.xsd">
    9. <debug:config dump-destination="tcp://%env(VAR_DUMPER_SERVER)%"/>
    10. </container>
  • PHP

    1. // config/packages/debug.php
    2. $container->loadFromExtension('debug', [
    3. 'dump_destination' => 'tcp://%env(VAR_DUMPER_SERVER)%',
    4. ]);

Outside a Symfony application, use the Symfony\Component\VarDumper\Dumper\ServerDumper class:

  1. require __DIR__.'/vendor/autoload.php';
  2. use Symfony\Component\VarDumper\Cloner\VarCloner;
  3. use Symfony\Component\VarDumper\Dumper\CliDumper;
  4. use Symfony\Component\VarDumper\Dumper\ContextProvider\CliContextProvider;
  5. use Symfony\Component\VarDumper\Dumper\ContextProvider\SourceContextProvider;
  6. use Symfony\Component\VarDumper\Dumper\HtmlDumper;
  7. use Symfony\Component\VarDumper\Dumper\ServerDumper;
  8. use Symfony\Component\VarDumper\VarDumper;
  9. $cloner = new VarCloner();
  10. $fallbackDumper = \in_array(\PHP_SAPI, ['cli', 'phpdbg']) ? new CliDumper() : new HtmlDumper();
  11. $dumper = new ServerDumper('tcp://127.0.0.1:9912', $fallbackDumper, [
  12. 'cli' => new CliContextProvider(),
  13. 'source' => new SourceContextProvider(),
  14. ]);
  15. VarDumper::setHandler(function ($var) use ($cloner, $dumper) {
  16. $dumper->dump($cloner->cloneVar($var));
  17. });

Note

The second argument of Symfony\Component\VarDumper\Dumper\ServerDumper is a Symfony\Component\VarDumper\Dumper\DataDumperInterface instance used as a fallback when the server is unreachable. The third argument are the context providers, which allow to gather some info about the context in which the data was dumped. The built-in context providers are: cli, request and source.

Then you can use the following command to start a server out-of-the-box:

  1. $ ./vendor/bin/var-dump-server
  2. [OK] Server listening on tcp://127.0.0.1:9912

DebugBundle and Twig Integration

The DebugBundle allows greater integration of this component into Symfony applications.

Since generating (even debug) output in the controller or in the model of your application may just break it by e.g. sending HTTP headers or corrupting your view, the bundle configures the `dump() function so that variables are dumped in the web debug toolbar.

But if the toolbar cannot be displayed because you e.g. called die()/exit()/`dd() or a fatal error occurred, then dumps are written on the regular output.

In a Twig template, two constructs are available for dumping a variable. Choosing between both is mostly a matter of personal taste, still:

  • {% dump foo.bar %} is the way to go when the original template output shall not be modified: variables are not dumped inline, but in the web debug toolbar;
  • on the contrary, {{ dump(foo.bar) }} dumps inline and thus may or not be suited to your use case (e.g. you shouldn’t use it in an HTML attribute or a <script> tag).

This behavior can be changed by configuring the debug.dump_destination option. Read more about this and other options in the DebugBundle configuration reference.

Tip

If the dumped contents are complex, consider using the local search box to look for specific variables or values. First, click anywhere on the dumped contents and then press Ctrl. + F or Cmd. + F to make the local search box appear. All the common shortcuts to navigate the search results are supported (Ctrl. + G or Cmd. + G, F3, etc.) When finished, press Esc. to hide the box again.

If you want to use your browser search input, press Ctrl. + F or Cmd. + F again while having focus on VarDumper’s search input.

New in version 4.4: The feature to use the browser search input was introduced in Symfony 4.4.

Using the VarDumper Component in your PHPUnit Test Suite

The VarDumper component provides a trait that can help writing some of your tests for PHPUnit.

This will provide you with two new assertions:

assertDumpEquals()

verifies that the dump of the variable given as the second argument matches the expected dump provided as the first argument.

assertDumpMatchesFormat()

is like the previous method but accepts placeholders in the expected dump, based on the `assertStringMatchesFormat() method provided by PHPUnit.

The VarDumperTestTrait also includes these other methods:

setUpVarDumper()

is used to configure the available casters and their options, which is a way to only control the fields you’re expecting and allows writing concise tests.

tearDownVarDumper()

is called automatically after each case to reset the custom configuration made in `setUpVarDumper().

New in version 4.4: The setUpVarDumper() andtearDownVarDumper() methods were introduced in Symfony 4.4.

Example:

  1. use PHPUnit\Framework\TestCase;
  2. use Symfony\Component\VarDumper\Test\VarDumperTestTrait;
  3. class ExampleTest extends TestCase
  4. {
  5. use VarDumperTestTrait;
  6. protected function setUp()
  7. {
  8. $casters = [
  9. \DateTimeInterface::class => static function (\DateTimeInterface $date, array $a, Stub $stub): array {
  10. $stub->class = 'DateTime';
  11. return ['date' => $date->format('d/m/Y')];
  12. },
  13. ];
  14. $flags = CliDumper::DUMP_LIGHT_ARRAY | CliDumper::DUMP_COMMA_SEPARATOR;
  15. // this configures the casters & flags to use for all the tests in this class.
  16. // If you need custom configurations per test rather than for the whole class,
  17. // call this setUpVarDumper() method from those tests instead.
  18. $this->setUpVarDumper($casters, $flags);
  19. }
  20. public function testWithDumpEquals()
  21. {
  22. $testedVar = [123, 'foo'];
  23. // the expected dump contents don't have the default VarDumper structure
  24. // because of the custom casters and flags used in the test
  25. $expectedDump = <<<EOTXT
  26. [
  27. 123,
  28. "foo",
  29. ]
  30. EOTXT;
  31. // if the first argument is a string, it must be the whole expected dump
  32. $this->assertDumpEquals($expectedDump, $testedVar);
  33. // if the first argument is not a string, assertDumpEquals() dumps it
  34. // and compares it with the dump of the second argument
  35. $this->assertDumpEquals($testedVar, $testedVar);
  36. }
  37. }

Dump Examples and Output

For simple variables, reading the output should be straightforward. Here are some examples showing first a variable defined in PHP, then its dump representation:

  1. $var = [
  2. 'a simple string' => "in an array of 5 elements",
  3. 'a float' => 1.0,
  4. 'an integer' => 1,
  5. 'a boolean' => true,
  6. 'an empty array' => [],
  7. ];
  8. dump($var);

../_images/01-simple.png

Note

The gray arrow is a toggle button for hiding/showing children of nested structures.

  1. $var = "This is a multi-line string.\n";
  2. $var .= "Hovering a string shows its length.\n";
  3. $var .= "The length of UTF-8 strings is counted in terms of UTF-8 characters.\n";
  4. $var .= "Non-UTF-8 strings length are counted in octet size.\n";
  5. $var .= "Because of this `\xE9` octet (\\xE9),\n";
  6. $var .= "this string is not UTF-8 valid, thus the `b` prefix.\n";
  7. dump($var);

../_images/02-multi-line-str.png

  1. class PropertyExample
  2. {
  3. public $publicProperty = 'The `+` prefix denotes public properties,';
  4. protected $protectedProperty = '`#` protected ones and `-` private ones.';
  5. private $privateProperty = 'Hovering a property shows a reminder.';
  6. }
  7. $var = new PropertyExample();
  8. dump($var);

../_images/03-object.png

Note

14 is the internal object handle. It allows comparing two consecutive dumps of the same object.

  1. class DynamicPropertyExample
  2. {
  3. public $declaredProperty = 'This property is declared in the class definition';
  4. }
  5. $var = new DynamicPropertyExample();
  6. $var->undeclaredProperty = 'Runtime added dynamic properties have `"` around their name.';
  7. dump($var);

../_images/04-dynamic-property.png

  1. class ReferenceExample
  2. {
  3. public $info = "Circular and sibling references are displayed as `#number`.\nHovering them highlights all instances in the same dump.\n";
  4. }
  5. $var = new ReferenceExample();
  6. $var->aCircularReference = $var;
  7. dump($var);

../_images/05-soft-ref.png

  1. $var = new \ErrorException(
  2. "For some objects, properties have special values\n"
  3. ."that are best represented as constants, like\n"
  4. ."`severity` below. Hovering displays the value (`2`).\n",
  5. 0,
  6. E_WARNING
  7. );
  8. dump($var);

../_images/06-constants.png

  1. $var = [];
  2. $var[0] = 1;
  3. $var[1] =& $var[0];
  4. $var[1] += 1;
  5. $var[2] = ["Hard references (circular or sibling)"];
  6. $var[3] =& $var[2];
  7. $var[3][] = "are dumped using `&number` prefixes.";
  8. dump($var);

../_images/07-hard-ref.png

  1. $var = new \ArrayObject();
  2. $var[] = "Some resources and special objects like the current";
  3. $var[] = "one are sometimes best represented using virtual";
  4. $var[] = "properties that describe their internal state.";
  5. dump($var);

../_images/08-virtual-property.png

  1. $var = new AcmeController(
  2. "When a dump goes over its maximum items limit,\n"
  3. ."or when some special objects are encountered,\n"
  4. ."children can be replaced by an ellipsis and\n"
  5. ."optionally followed by a number that says how\n"
  6. ."many have been removed; `9` in this case.\n"
  7. );
  8. dump($var);

../_images/09-cut.png

Learn More

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.