Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my VarDumper not working in Symfony2

Tags:

php

symfony

I've installed VarDumper using composer require. I've called the dump() function in my controller, this should work right?

composer require symfony/var-dumper

-

public function indexAction()
{
    $messages = Array(
            'x' => 'y',
            'a' => 'b',
            'c' => 'd'
            );

    dump($messages);
}

This is the error I get. But why can't I call dump in my controller?

Attempted to call function "dump" from namespace "App\Bundle\Controller".
like image 855
Angelo A Avatar asked May 01 '15 10:05

Angelo A


1 Answers

Development-like environments

Whithin a development-like envionment (development, test, etc), you have to make sure the DebugBundle is enabled in the application kernel:

The DebugBundle integrates the VarDumper component in Symfony applications. All these options are configured under the debug key in your application configuration.

Solution

// app/AppKernel.php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            // ...
        );

        if (in_array($this->getEnvironment(), array('dev', 'test'))) {
            $bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
            // ...
        }
    }

    // ...
}

Production-like environments

This is a bad practice to dump variables in a production environment but some situations can't fit best practices.

Depending on the environment, there may be multiple declarations of the global function dump() (in pear/XML, pear/adobd, etc). Moreover if you look closely at the new Symfony dump() function declaration, it is created only if it doesn't already exist:

if (!function_exists('dump')) {
    /**
     * @author Nicolas Grekas <[email protected]>
     */
    function dump($var)
    {
        foreach (func_get_args() as $var) {
            VarDumper::dump($var);
        }
    }
}

Solution

So the good solution is to directly call VarDumper::dump() from the namespace Symfony\Component\VarDumper\VarDumper. I also suggest to wrap it inside an exit() to avoid unexpected behaviours:

use Symfony\Component\VarDumper\VarDumper;

class myClass
{
    function myFunction()
    {
        exit(VarDumper::dump(...));
    }
}
like image 152
Ivan Gabriele Avatar answered Oct 11 '22 04:10

Ivan Gabriele