PHP
Article

No More var_dump – Introducing Symfony VarDumper!

By Bruno Skvorc

Recently, Symfony went from Zend-like bloat and rigidity to extreme decoupling and modularity. With the new Developer Experience initiative, Symfony has done a Laravel-style 180° and dove right into making its components more end-user friendly, its docs more complete, and its AppBundles unbundled, simplifying entry and further development almost exponentially. Considering user friendliness, it’s a long way from “best pals friendly” but it’s definitely no longer hostile. One factor that contributes to this factor a lot is their continuous pushing out of new components that are incredibly useful outside of Symfony’s context. One such component is the new VarDumper.

symfony-logo

Why?

You’re developing a feature. You either don’t feel like writing tests, or what you’re developing needs some variable testing in the middle of a function – something you can’t quite cover with a test. Inevitably, you resort to something like die(var_dump($var));. Even if you’ve abstracted it into a shorthand method like vddd($var), it’s still clumsy and unreadable almost as much as the monochromatic output it generates.

There’s little choice in the matter – sometimes we simply need our vddds. And sure, if you’re an Xdebug user, you’re probably used to a slightly better looking output than the raw PHP prints. Still, few good solutions existed that beautified this output for us enough to make it worth installing a dev dependency. Until VarDumper.

What is VarDumper?

Symfony VarDumper is a component designed to replace your var_dumps. It performs essentially the same functionality, but provides you with much, much more information in a much prettier format. It’s the var_dump you’ve always wanted.

As per their documentation, 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.

Installing and Using

Let’s quickly install it into our Homestead Improved instance and run a couple of tests. If you’re not familiar with HI yet, please take 5 minutes to get it over with so you can follow along with the tests.

Installation

As with any decent modern PHP project, installing is as simple as running

composer require symfony/var-dumper

Usage examples

It’s used via the newly exposed dump function:

$var1 = "test";

dump($var1);

01

Let’s try something more complex now.

$a = [
    'ak1' => 'av1',
    'ak2' => 'av2',
    'ak3' => 'av3',
    'ak4' => 'av4',
    'ak5' => 'av5',
];

$b = [
    'bk1' => 'bv1',
    'bk2' => 'bv2',
    'bk3' => 'bv3',
    'bk4' => 'bv4',
    'bk5' => 'bv5',
];

$object = new \stdClass();
$object->prop1 = 10;
$object->prop2 = 20;
$object->prop3 = 30;
$object->prop4 = 40;

$c = [
    'a' => &$a,
    'b' => $b,
    $object
];

dump($c);

01

As you can see, VarDumper wonderfully exports the variables we defined, declaring everything verbosely – all coupled with some practical CSS that not only syntax highlights everything but also allows us to expand and collapse various parts of the data dump. Hmm, but what are those plusses next to the properties of the stdObject? Public properties? How does it display private ones, then? Does it at all? Let’s see.

class Test {
    public $prop1 = 10;
    private $prop2 = 20;
    protected $prop3 = 30;
    private $prop4 = 40;

    public function __construct($value) {
        $this->undefinedProp = $value;
    }
}

$t = new Test(50);

dump($t);

02

So public properties are plusses, private ones are minuses, protected ones are hashes, neat. Not only that, but every dumped property also has a title hint which exposes more information when you hover your mouse over them:

02

What’s more, runtime added properties are specifically defined in both the hint, and visually – they’re surrounded by quotes.

What about runtime added methods? Let’s see.

class Test {
    public $m1;
    protected $m2;

    public function __construct() {
        $this->m2 = function() {
            return "I'm method 2";
        };
    }

    public function buildFunction() {
        $this->m3 = function() {
            return "I'm method 3";
        };
    }

    public function __call($method, $args)
    {
        if (isset($this->$method)) {
            $func = $this->$method;
            return call_user_func_array($func, $args);
        }
    }

}

$t = new Test();
$m1 = function() {
    return "I'm method 1";
};
$t->m1 = $m1;
$t->buildFunction();
$t->m1();

dump($t);

03

You can see VarDumper exposes much more information about objects, using reflection, than the typical var_dump – even the lines of code where the methods are defined.

These are just some of the nifty tricks VarDumper has up its sleeve – for the rest, and screenshots of how they look, check the announcement post out.

Conclusion

VarDumper is a great tool for quick and dirty safety and sanity checks, and when used in conjunction with Symfony’s DebugBundle, it becomes even more powerful – in fact, it’s included by default in dev and debug versions of Symfony installations, from version 2.6 onward.

Some might argue that using it with a simple non namespaced dump() command has the potential to cause conflicts with other utility methods you might have in your project, and it obscures its source on first glance. While a changeable function name to call the utility might allay those worried minds, I believe we’re dealing with very rudimentary and production-insignificant functionality here, and thus this non-issue may be forgiven.

Now that you know about VarDumper, will you be adding it to your own projects for on-the-fly debugging purposes?

Comments
TaylorRen

This is a long missing feature. Tried in my Silex application:

use Symfony\VarDumper;

...

dump($var);

majkel

You should encourage people to use proper tools for this kind of work, like xdebug.
From mine experience south debugging code often ends up on the production.
Using debugger one could inspect every variable (see value and type), check execution path or find places where some code is being invoked (breakpoints + call stack -> very useful for reverse-engineering)

swader

Performance hits and installation of extensions (shared hosting friendly, I guess?)

Also, in small throwaway projects, sometimes setting up Xdebug properly isn't worth the time and effort. If I'm testing a tutorial demo and checking for bugs, I'll have a throwaway vagrant box defined which I can scratch after I'm done. The entire ordeal probably wouldn't take more than 20 minutes, which is far too short to set up Xdebug anyway.

majkel

That's true, especially performance hit. I usually turn on xdebug extension only for debugging sessions.

Does any IDE has support for build-in php 5.6 debugger ?

StarLion

So... it makes a pretty var_dump. Doesnt remove any code (in fact, adds a line).

If your dump is several layers deep, you've got to click around and open all the layers to find what you're looking for. Assuming you actually know what you're looking for ahead of time.

Or... i could just View Source a var_dump.

resting

Interesting package. I've added it to a laravel app, but a dump() of a eloquent collection with 150 over items only has the 1st five expandable. The rest were truncated with ....
Any idea how to configure VarDumper to show all details instead of truncating them?

swader

Hmm, not right now. Let us know if you find an easy way.

swader

Maybe something along these settings might help. You might have to find a way to feed it the configuration, though, since this applies only to when it's used within the DebugBundle.

raveren

Disclaimer: author of Kint here.

I'd just like to encourage those who have not heard of it, check Kint out:

https://github.com/raveren/kint/tree/1.0.0-wip

It's been in the works for years, has tons of useful features like keyboard navigation, plain text alternative, trace output and so on, and most importantly - it's effortless to install and use. Composer support is there, but highly optional - and Kint even supports PHP5.2 when you're stuck with terrible old projects. Needless to say, every later major version is supported and provides more functionality.

swader

Looks good, thanks for chiming in! A "battle of the vardumpers" article might not be a bad idea smile

nicolasgrekas

As the main author of the VarDumper component, thank you for this article!
If you really plan to write a "battle of the vardumpers", let me know smile
One main example with all other dumpers is how (hard) references are dumped: with VarDumper, you can inspect/read them. With others, they are at best replaced by a recursion warning.

VarDumper is focused on extracting the highest possible accuracy about any PHP variable. It never fails with highly complex structures nor in any layer of your PHP app (try e.g. dumping in a PHP output buffering handler).

VarDumper is also highly modular so you could build more than one dumper (I would even encourage LadyBug/Kint to build theirs on the state extraction mechanism of VarDumper).

Debugging can't be done efficiently without robust tools. The xdebug vs dumpers discussion will never end imho because both serve different use cases / group of users (I personally use the two of them).

For Silex integration, you should try https://github.com/jeromemacias/Silex-Debug
And for the ellipsis that show up too fast, I've raised the default 250 items limit to 2500, that should help.

swader

Thanks for chiming in! I actually am planning to do a battle of the VarDumpers, for real smile Just need a good scenario that tests them all. Ideas welcome smile

Michael_Morris

Regardless of the debugger you choose, loading the debug library with the php auto prepend file directive is highly useful. I know of no community frameworks that make use of that directive and in ten years I've only seen one custom program use it.

This approach insures you won't accidentally push debug code live since the two are segregated.

keyboSlice

+1 for Kint, it's awesome, thank you for taking the time to create it Raveren

Mohamed_Ragab_Dahab

Guys, i think this tool and this article mainly wrote for Symfony2 developers as using the native var_dump() against Symfony2 Objects is horrible, so they tried to fix this and address it to us in a political way.

anyways i really helps when developing using Symfony2

majkel

Topic is quite old but I would like to clarify. PhpStorm - as any other PHP IDE - does not support phpdbg yet. But development is ongoing https://youtrack.jetbrains.com/issue/WI-21414.

Ciki

@swader don't forget Tracy for the VarDumpers battle wink

swader

Thanks, I'll keep it in mind!

Michael_Morris

I ran into this thing and it got me away from using my handmade suite - that's a feat right there. I'm incorporating it into a patch I'm writing for Drupal 8 to improve how the stacks are dumped on the error event when the system is configured into dbug mode. It'd definitely a help there since drupal's objects are huge and massively recursed.

peter_indexed

One should always pick a debugging solution that would work without changing the codebase back and forth. Any kind of var_dump should never be available on production. Any method used should always include a production check and disablee the output eg. if (PRODUCTION) dont dump.

Michael_Morris

Last time I checked it was fully possible run any one of a number of PHP's debug statements on a production box if you're foolish enought to do so. How is this any different?

Ironically I had this discussion with my boss eariler today. I give you the same challenge as I gave him - how is this any more destructive or harmful than leaving a print_r(); exit; series in the code?

Answer, it isn't.

Keeping test code separate from production code is an issue beyond the scope of what this tool addresses.

peter_indexed

using print_R() and exit is just as harmful as I have cleaned up the code on production when those debug statements got released on production.

I dont say you shouln't use them but always do something like this instead:

if (!empty($_GET['we_are_debugging'])) {
   print_R('data');die()
}

with that simple check you can debug on local and production still continues to work.

That being said, your unit tests should catch it before that though

EDIT
This post has been reformatted by enclosing the code block in 3 backticks
```
on their own lines.

Michael_Morris

Then you're permanently wasting code cycles on the eval of the conditional. And who would ever use a $_GET var to determine debug mode? Talk about rolling out the red carpet to hackers...

abyshakes

Thanks for this !! I'm just switching from kint smile +1 for kint too

Also just thought I'll mention it on this thread that VarDumper works awesome on the console with some good color coding !!

Cheers

Recommended
Sponsors
Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in PHP, once a week, for free.