为什么我的VarDumper无法在Symfony2中运行

Ang*_*o A 13 php symfony

我已经使用composer require安装了VarDumper.我在我的控制器中调用了dump()函数,这应该可行吗?

composer require symfony/var-dumper
Run Code Online (Sandbox Code Playgroud)

-

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

    dump($messages);
}
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误.但为什么我不能在我的控制器中调用dump?

Attempted to call function "dump" from namespace "App\Bundle\Controller".
Run Code Online (Sandbox Code Playgroud)

小智 22

确保在应用程序的内核中启用了DebugBundle

// 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();
            // ...
       }
    }

    // ...
}
Run Code Online (Sandbox Code Playgroud)

  • 实际上这个答案是正确的.选择的答案允许你使它工作,但这个使得直接使用dump()函数 (4认同)
  • 谢谢,当从2.3升级时,我错过了Bundle. (2认同)

Iva*_*ele 21

类似开发的环境

在类似开发的环境(开发,测试等)中,您必须确保在应用程序内核中启用DebugBundle:

DebugBundle在Symfony应用程序中集成了VarDumper组件.所有这些选项都在应用程序配置中的调试密钥下配置.

// 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();
            // ...
        }
    }

    // ...
}
Run Code Online (Sandbox Code Playgroud)

类似生产的环境

在生产环境中转储变量是一种不好的做法,但某些情况不适合最佳实践.

根据环境的不同,有可能是全局函数的多个声明dump()(中pear/XML,pear/adobd等).此外,如果仔细查看新的Symfony dump()函数声明,只有在它尚不存在时才会创建它:

if (!function_exists('dump')) {
    /**
     * @author Nicolas Grekas <p@tchwork.com>
     */
    function dump($var)
    {
        foreach (func_get_args() as $var) {
            VarDumper::dump($var);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

所以好的解决方案是直接VarDumper::dump()从命名空间调用Symfony\Component\VarDumper\VarDumper.我还建议将其包装在内exit()以避免意外行为:

use Symfony\Component\VarDumper\VarDumper;

class myClass
{
    function myFunction()
    {
        exit(VarDumper::dump(...));
    }
}
Run Code Online (Sandbox Code Playgroud)