【问题标题】:Symfony After Filters - modify json responseSymfony After Filters - 修改 json 响应
【发布时间】:2015-12-29 12:39:35
【问题描述】:

有谁知道如何在不删除旧数据的情况下在过滤器 (onKernelResponse) 中将新数据字段添加到现有 JsonResponse (Symfony\Component\HttpFoundation\JsonResponse) 中?

例如,我有自定义控制器

<?php
class MessageController extends Controller
{

    public function getAllMessagesAction(Request $request)
    {
        (...)

        return new JsonResponse(array(
            'count' => count($messages),
            'total_count' => $allMessagesCount,
            'messages' => $messages,
        ));
    }
}

还有一些听众

<?php
class NotesListener
{
    public function onKernelResponse(FilterResponseEvent $event)
    {
        (...)

        $response = $event->getResponse();
        if ($response instanceof JsonResponse) {
            $response->setData(array('foo' => 'bar'));
        }
    }
}

问题

问题是监听器中的$response-&gt;setData 会覆盖控制器中传递的数据。此外,JsonResponse 没有像addData() 这样的方法。不幸的是没有方法getData(),所以我无法获取旧数据,修改它,设置新数据。

有谁知道好的解决方案吗?

提前致谢!

【问题讨论】:

  • 你真的很接近,但你正在寻找的方法被称为setContent()getContent()。也是 JsonResponse 的 see the API docs

标签: php json symfony


【解决方案1】:

您可以使用getContent()对数据进行解码,然后修改并重新设置数据。

或者,您可以将控制器更改为仅返回数据并在事件侦听器中创建 JsonResponse

【讨论】:

  • 是的,json_decode($response-&gt;getContent(), true); 似乎是最好的解决方案。但另一方面,如果会有多个侦听器并且响应内容将包含超过 1k 的元素怎么办?这可能会减慢整个应用程序的速度。我现在在想,也许更好的方法是用自己的类扩展JsonResponse 并添加getData 方法?
猜你喜欢
  • 2016-04-10
  • 2012-03-14
  • 2020-01-19
  • 2013-03-04
  • 2014-09-16
  • 2016-12-29
  • 2017-08-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多