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

时间:2015-05-01 10:06:02

标签: php symfony

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

composer require symfony/var-dumper

-

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

    dump($messages);
}

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

Attempted to call function "dump" from namespace "App\Bundle\Controller".

4 个答案:

答案 0 :(得分: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();
            // ...
       }
    }

    // ...
}

答案 1 :(得分:19)

类似开发的环境

在类似开发的环境(开发 test 等)中,您必须确保在应用程序内核中启用DebugBundle:< / p>

  

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

    // ...
}

类似生产的环境

这是在生产环境中转储变量的不良做法,但某些情况不适合最佳做法。

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

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

<强>解决方案

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

use Symfony\Component\VarDumper\VarDumper;

class myClass
{
    function myFunction()
    {
        exit(VarDumper::dump(...));
    }
}

答案 2 :(得分:0)

composer global require symfony / var-dumper

您将看到:更改了当前目录(GLOBAL_COMPOSER_DIRECTORY)

在你的php.ini中: auto_prepend_file =(GLOBAL_COMPOSER_DIRECTORY)/vendor/autoload.php

然后,您可以在所有项目中使用dump而无需安装

答案 3 :(得分:-2)

尝试使用命令php composer.phar update更新项目的依赖项。该命令必须在composer require symfony/var-dumper之后运行。