![](/img/trans.png)
[英]Symfony 2.1 - Creating authentication listener with JMS\DiExtraBundle
[英]Symfony 2.1 - Custom Json Annotation Listener
对于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));
}
}
}
}
这是我对侦听器的定义。
json.listener:
class: Company\Bundle\Listener\Response\Json
arguments: [@service_container]
tags:
- { name: kernel.event_listener, event: kernel.view, method: onKernelView }
我显然在这里丢失了一些东西,因为它已注册为kernel.view侦听器。 如何更改它,以便仅在控制器动作上存在@Json()注释时才调用它?
不能假装是确定的答案。
我不确定为什么要扩展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
转储它们)。
如果不起作用,请尝试在此处添加一些调试和打印语句(在供应商文件夹中找到ControllerListener.php
):
var_dump(array_keys($configurations)); // Should contain _json
请记住在编辑之前对其进行复制,否则Composer在更新依赖项时会抛出错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.