No More var_dump – Introducing Symfony VarDumper!

Share this article

Key Takeaways

  • Symfony’s VarDumper is a new component designed to replace the traditional var_dump in PHP, providing a more user-friendly, comprehensive and visually appealing output. This tool is especially useful for developers needing variable testing within a function, producing a more readable output than raw PHP prints.
  • The VarDumper can be installed simply by running ‘composer require symfony/var-dumper’ and is used via the newly exposed dump function. It provides a per object and resource types specialized view, configurable output formats, the ability to dump internal references, and can operate in the context of an output buffering handler.
  • VarDumper is included by default in dev and debug versions of Symfony installations from version 2.6 onward. It is a powerful tool for quick and dirty safety and sanity checks, and is especially powerful when used in conjunction with Symfony’s DebugBundle. It can be used for on-the-fly debugging in projects.

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?

Frequently Asked Questions (FAQs) about Symfony VarDumper

What is Symfony VarDumper?

Symfony VarDumper is a component that aims to replace var_dump(), print_r() and debug_zval_dump() functions in PHP. It provides a better and more readable output of variables, objects, and resources. It’s particularly useful for debugging purposes as it allows you to dump information about a variable in a more structured and styled format.

How do I install Symfony VarDumper?

You can install Symfony VarDumper using Composer, a tool for dependency management in PHP. Run the following command in your project directory: composer require symfony/var-dumper. This will add the VarDumper component to your project.

How do I use the dump() function in Symfony?

Once you’ve installed the VarDumper component, you can use the dump() function to output information about a variable. For example, dump($variable);. This will output detailed information about the variable in a structured and styled format.

How can I control the depth of the dump output?

You can control the depth of the dump output by using the setMaxDepth() method. For example, dump($variable)->setMaxDepth(2);. This will limit the output to a depth of 2 levels.

How can I use VarDumper in a Symfony project?

In a Symfony project, the VarDumper component is automatically registered as a service. You can use the dump() function in your controllers, templates, and services.

How can I use VarDumper in a non-Symfony project?

In a non-Symfony project, you need to require the VarDumper component’s autoloader. Add the following line at the beginning of your script: require 'vendor/autoload.php';. Then, you can use the dump() function as usual.

How can I dump variables to the browser’s console?

You can dump variables to the browser’s console using the dump() function and the toScript() method. For example, dump($variable)->toScript();. This will output the information in the browser’s console instead of the HTML output.

How can I dump variables to the log?

You can dump variables to the log using the dump() function and the toLog() method. For example, dump($variable)->toLog();. This will output the information in the log file instead of the HTML output.

How can I customize the style of the dump output?

You can customize the style of the dump output by using the setStyle() method. For example, dump($variable)->setStyle('key', 'color:blue');. This will change the color of the keys in the output to blue.

How can I use VarDumper in a production environment?

In a production environment, you should avoid using the dump() function as it can reveal sensitive information. However, if you need to use it, make sure to disable the HTML output by using the setHtmlDump(false) method. For example, dump($variable)->setHtmlDump(false);. This will output the information in plain text format.

Bruno SkvorcBruno Skvorc
View Author

Bruno is a blockchain developer and technical educator at the Web3 Foundation, the foundation that's building the next generation of the free people's internet. He runs two newsletters you should subscribe to if you're interested in Web3.0: Dot Leap covers ecosystem and tech development of Web3, and NFT Review covers the evolution of the non-fungible token (digital collectibles) ecosystem inside this emerging new web. His current passion project is RMRK.app, the most advanced NFT system in the world, which allows NFTs to own other NFTs, NFTs to react to emotion, NFTs to be governed democratically, and NFTs to be multiple things at once.

BrunoSdebuggingframeworksymfony
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week