Symfony içinde bir event listener ile controllerden gelen cevabı yakalayıp istediğiniz gibi değişiklikler yapabilirsiniz. Bu örnekte sadece header bilgilerine ekleme yapacağız.


Controller


namespace Application\ServerBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
* @Route("api", service="application_server.controller.api")
*/
class ApiController extends Controller
{
/**
* @param Request $request
*
* @Method({"POST"})
* @Route("")
*
* @return Response
*/
public function indexAction(Request $request)
{
.....

return new Response(...);
}
}

services:
application_server.controller.api:
class: Application\ServerBundle\Controller\ApiController

Test


* HTTP/1.1 200 OK
* Date: Thu, 05 Jan 2017 16:27:21 GMT
* Server Apache/2.4.12 (Ubuntu) is not blacklisted
* Server: Apache/2.4.12 (Ubuntu)
* Vary: Authorization
* Cache-Control: no-cache
* X-Debug-Token: f0bb9d
* X-Debug-Token-Link: http://api.dev/app_dev.php/_profiler/f0bb9d
* Content-Length: 35
* Content-Type: text/html; charset=UTF-8

Event Listener


namespace Application\ServerBundle\EventListener;

use Symfony\Component\HttpKernel\Event\FilterResponseEvent;

class ResponseInterceptorListener
{
public function onKernelResponse(FilterResponseEvent $event)
{
// You can do more check here such as:
// Is it master request?
// Is it a specific controller?
// Is it a authenticated user?
// So on.

$response = $event->getResponse();
$response->headers->set('My-Hello-Message', 'Hello Inanzzz');
}
}

services:
application_server.listener.response_interceptor:
class: Application\ServerBundle\EventListener\ResponseInterceptorListener
tags:
- { name: kernel.event_listener, event: kernel.response, method: onKernelResponse }

Test


* HTTP/1.1 200 OK
* Date: Thu, 05 Jan 2017 16:29:11 GMT
* Server Apache/2.4.12 (Ubuntu) is not blacklisted
* Server: Apache/2.4.12 (Ubuntu)
* Vary: Authorization
* Cache-Control: no-cache
* My-Hello-Message: Hello Inanzzz
* X-Debug-Token: f0bb9d
* X-Debug-Token-Link: http://api.dev/app_dev.php/_profiler/f0bb9d
* Content-Length: 35
* Content-Type: text/html; charset=UTF-8