The Slim Framework support forum has moved to http://discourse.slimframework.com. This Tender forum is no longer maintained or monitored.

Echo in middleware

james poon's Avatar

james poon

23 Feb, 2016 05:06 PM

I am trying to find out how middleware than I find this issue:

$app->add(function(ServerRequestInterface $request, ResponseInterface $response, $next){
            echo '1<br/>';
            //$response->getBody()->write('1<br/>');
            $response = $next($request, $response);
            //$response->getBody()->write('2<br/>');
            echo '2<br/>';
            return $response;
        })->add(function(ServerRequestInterface $request, ResponseInterface $response, $next){
            //$response->getBody()->write('3<br/>');
            echo '3<br/>';
            $response = $next($request, $response);
            //$response->getBody()->write('4<br/>');
            echo '4<br/>';
            return $response;
        });
$app->get('/', function($r, $rp, $args){
    echo 'index';
});

the output by echo is: 3 1 2 4 index
the output by $response->getBody()->write() is: 3 1 index 2 4

why output by $response->getBody()->write() gets different output compare with echo? Instead of echo after $next(), will an instruction, like a function call, also be executed before the execution of echo 'index' ?

  1. 1 Posted by Rob Allen on 23 Feb, 2016 05:40 PM

    Rob Allen's Avatar

    The echos are captured by the output buffer (https://github.com/slimphp/Slim/blob/3.x/Slim/Route.php#L324) and prepended to the body here https://github.com/slimphp/Slim/blob/3.x/Slim/Route.php#L345

    i.e. don't use echo.

Reply to this discussion

Internal reply

Formatting help / Preview (switch to plain text) No formatting (switch to Markdown)

Attaching KB article:

»

Attached Files

You can attach files up to 10MB

If you don't have an account yet, we need to confirm you're human and not a machine trying to post spam.

Keyboard shortcuts

Generic

? Show this help
ESC Blurs the current field

Comment Form

r Focus the comment reply box
^ + ↩ Submit the comment

You can use Command ⌘ instead of Control ^ on Mac