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".
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();
// ...
}
}
// ...
}
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(...));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With