3

What is the correct way to stop code execution after sending Response headers, but without using exit()?

I know the script SHOULD return a Response, but how can I force it to be returned from outside of a Controller, for example from a service?

Lets say my service's method does return a Response this way:

return RedirectResponse($url)->send();

But in another place it can return other things. So what I can do is to check what it does actually return:

$result = $myService->doSomething();
if ($result instanceof RedirectResponse) {
    return $result;
}

What I want to achieve is to avoid checking result type in every place where I use my service, BUT I would like to see the returned response in Profiler/logs (if I use exit() I can't).

Is there a way to force kernel terminate?


EDIT:

Actually the service is used in event before any controller, so I want to do redirect before any controller execution. So maybe a way to omit controller execution?

Jarek Jakubowski
  • 948
  • 10
  • 22

2 Answers2

1

A controller is a PHP callable you create that takes information from the HTTP request and creates and returns an HTTP response (as a Symfony Response object).

The only concern for a Controller is to process a request and return a response. Having a Service handle a Response object is probably a bad design choice.

In any case, you could just die/exit your controller and use Kernel events to hook in the Request/Response flow and inspect the returned Response. Probably the terminate event is the right choice http://symfony.com/doc/current/components/http_kernel/introduction.html

Diego Ferri
  • 2,657
  • 2
  • 27
  • 35
  • Actually the service is used in event before any controller, so I want to do redirect before any controller execution. I just wanted to make the question more general. – Jarek Jakubowski Jul 23 '15 at 11:02
  • Updated the question. – Jarek Jakubowski Jul 23 '15 at 11:10
  • 1
    Ok, got it! At the same page you can find even the request event. It should be what are you searching for. http://symfony.com/doc/current/components/http_kernel/introduction.html#the-kernel-request-event – Diego Ferri Jul 23 '15 at 13:24
1

Ok, I found a way to do it. All I had to do is to terminate the kernel before exit - it does dispatch all after-response events (like profiling, logging etc.).

$response = new RedirectResponse($url);
$response->send();
$kernel->terminate($request, $response);
exit();

If anyone would found better way do to this, please answer so I can switch the mark.

Jarek Jakubowski
  • 948
  • 10
  • 22