phpsymfonysymfony-http-foundation

Symfony2: force stop code execution after sendiing Response headers


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?


Solution

  • 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.