Search code examples
phpslim

What is the purpose of the buffer functions used in Slim PHP codebase?


I am going the codebase of slim php for educational purposes, I kind of understand alot from reading it. however, i am finding it really difficult to understand the purpose of the buffer used in the 'main' run method of the App class.

public function run($silent = false)
{
    $response = $this->container->get('response');

    try {
        ob_start();
        $response = $this->process($this->container->get('request'), $response);
    } catch (InvalidMethodException $e) {
        $response = $this->processInvalidMethod($e->getRequest(), $response);
    } finally {
        $output = ob_get_clean();
    }

    if (!empty($output) && $response->getBody()->isWritable()) {
        $outputBuffering = $this->container->get('settings')['outputBuffering'];
        if ($outputBuffering === 'prepend') {
            // prepend output buffer content
            $body = new Http\Body(fopen('php://temp', 'r+'));
            $body->write($output . $response->getBody());
            $response = $response->withBody($body);
        } elseif ($outputBuffering === 'append') {
            // append output buffer content
            $response->getBody()->write($output);
        }
    }

    $response = $this->finalize($response);

    if (!$silent) {
        $this->respond($response);
    }

    return $response;
}

i have tried to dump the value of ob_get_clean() but it is always empty.


Solution

  • This is done in order to always return a PSR-7 Response. If you echo or print_r() inside your routes/middleware this will get prepended to the response body if the outputBuffering setting is set to prepend or if set to append it will be appended.