How to process after run() method?

After call $app->run(); I want to call memory_get_peak_usage() to see real memory usage at the bottom of the page.
Example: </html><!-- max memory usage 3722872 Bytes-->
The max memory usage is already in the middleware but it is not real memory usage because it is not called at the end of process which is should be after run() method.

How to process after run() method?


<?php

use \Psr\Http\Message\ServerRequestInterface;
use \Psr\Http\Message\ResponseInterface;


/**
 * Display profiler at the end of response.
 *
 * @author Vee W.
 */
class DisplayProfiler
{


    /**
     * Invokable class.<br>
     * Display profiler at the bottom of the page content or end of response.
     * 
     * @param ServerRequestInterface $request
     * @param ResponseInterface $response
     * @param \System\Middleware\callable $next
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
    {
        $display_result = '<!-- max memory usage ' . memory_get_peak_usage() . 'Bytes -->;
        
        $response = $next($request, $response);
        $content = (string)$response->getBody();

        if (is_string($content)) {
            $content_with_profiler = $content . $display_result;
        }

        unset($content);

        if (isset($content_with_profiler)) {
            $response->getBody()->rewind();
            $response->getBody()->write($content_with_profiler);
        }

        unset($content_with_profiler, $display_result);
        return $response;
    }// __invoke


}

My middleware.

<?php
$app->add(new \System\Middleware\DisplayProfiler());
$app->run();

index.php

<?php
'displayErrorDetails' => true,
'addContentLengthHeader' => false,

app config

Hello Vee,

I don’t think you can use middleware to hook in at the end of the process or even after App::run.
I think the easiest way would be to add the content after the app->run(); call, e.g.

$app->run();
print '<!-- max memory usage ' . memory_get_peak_usage() . 'Bytes -->';

I think this will get you the most accurate for the peak memory usage.

Note that you will need to set the addContentLengthHeader setting to false, otherwise the line will not show up in your browser.

Another way would be to extend \Slim\App and override App::respond, which is called pretty at the end of App::run.

1 Like

Yes, thank you .
Change addContentLengthHeader works fine.

1 Like