Search code examples
phpsymfonyob-start

usage of ob_start function


I'm following this tutorial https://symfony.com/doc/current/create_framework/front_controller.html I have a simple question about this php code

 // example.com/web/front.php
require_once __DIR__.'/../vendor/autoload.php';

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

$request = Request::createFromGlobals();
$response = new Response();

$map = [
    '/hello' => __DIR__.'/../src/pages/hello.php',
    '/bye'   => __DIR__.'/../src/pages/bye.php',
];

$path = $request->getPathInfo();
if (isset($map[$path])) {
    ob_start();
    include $map[$path];
    $response->setContent(ob_get_clean());
} else {
    $response->setStatusCode(404);
    $response->setContent('Not Found');
}

$response->send();

the code works without buffering the output (without with ob_ calls ... ), so my question is why ?


Solution

  • output buffering takes what is echoed between ob_start() and ob_get_clean() (or other output buffering ends) and prevents it from "early leaking" into the response that php serves to the user.

    If you remove output buffering, the content of the response is just output "conventionally", however the $response object would be empty, $reponse->send() would fail, because you already output other stuff, so headers can't be sent anymore.

    So, it works, because you either send the output directly (php's default mode of operation), or you buffer the ouput and send that output "indirectly" via the response object (or by just outputting the return value of ob_get_clean).

    the main difference in my opinion is that the framework stuff, that might or might not add some utility to a response, can't do anything anymore, because the framework doesn't know what output you've send. the full symfony framework for example displays a profiler bar at the bottom, which it surely does by injecting it in the response. By circumventing the $response object, you also deny the injection. however, in your particular case, it might not matter at all.