Symfony 2.1 - 自定义Json注释监听器

时间:2013-02-20 21:53:41

标签: php symfony symfony-2.1

对于Symfony 2.1项目,我正在尝试创建一个新的注释@Json(),它将注册一个监听器,当我返回一个数组时,该监听器将自动创建JsonResponse对象。我已经有了它的工作,但由于某种原因,监听器始终被调用,即使在没有@Json注释的方法上也是如此。我假设我的方法有效,因为Sensio额外的捆绑包使用@Template注释。

这是我的注释代码。

<?php

namespace Company\Bundle\Annotations;

/**
 * @Annotation
 */
class Json extends \Sensio\Bundle\FrameworkExtraBundle\Configuration\ConfigurationAnnotation
{
    public function getAliasName()
    {
        return 'json';
    }
}

这是我的听众代码。

<?php

namespace Company\Bundle\Listener\Response\Json;

class JsonListener
{
    //..

    public function onKernelView(GetResponseForControllerResultEvent $event)
    {
        $request = $event->getRequest();
        $data = $event->getControllerResult();

        if(is_array($data) || is_object($data)) {
            if ($request->attributes->get('_json')) {
                $event->setResponse(new JsonResponse($data));
            }
        }
    }
}

这是我对听众的yaml定义。

json.listener:
            class:      Company\Bundle\Listener\Response\Json
            arguments:  [@service_container]
            tags:
                - { name: kernel.event_listener, event: kernel.view, method: onKernelView }

我显然在这里遗漏了一些东西,因为它被注册为kernel.view监听器。如何更改它以便仅在控制器操作上出现@Json()注释时调用它?

1 个答案:

答案 0 :(得分:1)

不要假装是明确的答案。

我不确定你为什么要扩展ConfigurationAnnotation:它的构造函数接受array,但你的注释不需要任何配置。相反,实施ConfigurationInterface

namespace Company\Bundle\Annotations;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\ConfigurationInterface;

/**
 * @Annotation
 */
class Json implements ConfigurationInterface
{
    public function getAliasName()
    {
        return 'json';
    }

    public function allowArray()
    {
        return false;
    }
}
来自SensionFrameworkExtraBundle的 Sensio ControllerListener将读取您的注释(使用方法注释合并类)并执行此检查:

if ($configuration instanceof ConfigurationInterface) {
    if ($configuration->allowArray()) {
        $configurations['_'.$configuration->getAliasName()][] = $configuration;
    } else {
        $configurations['_'.$configuration->getAliasName()] = $configuration;
    }
}

设置前缀为_的请求属性。您正在检查_json,因此它应该可以正常工作。尝试在视图事件侦听器中转储$request->attributes。确保您的json.listener服务也已正确加载(使用php app/console container:debug >> container.txt转储)。

如果它不起作用,请尝试添加一些调试和打印语句here(在供应商文件夹中查找ControllerListener.php):

var_dump(array_keys($configurations)); // Should contain _json

请记住在编辑之前复制它,否则更新依赖项时Composer会抛出并出错。