Slim 3 - Possible to call a function/method AFTER response is sent?

Im wondering if there is a way to (on a specific route) call a method after the response has been sent.

I see the example given for the Route Middleware:

$app->get(’/’, function ($request, $response, $args) {
$response->getBody()->write(’ Hello ');
return $response;
})->add($mw);

But that obviously can apply changes to the response before it is sent - which implies that it is response blocking.

I am wanting to do some logging after the response is sent so as to not hold up the response while Im doing the logging.

So, in other words.

  1. get response
  2. grab some data from the response
  3. send the response
  4. do some extra stuff with the data I grabbed in #2

Is this possible?

Thanks.

3+4) That’s not how Slim and PHP in general work.

I think you are looking for an “outgoing” middleware to handle the logging.

Take a look at the ExampleAfterMiddleware.

First, thanks for the reply. Second, I dont understand.

PHP doesnt automatically halt execution when it sends a response code. Right?

If not, then why cant it continue after sending a response?

As I mentioned, the “after route” middleware seems to actually be a “before response” call - unless I am misreading it.

The documentation shows the ExampleBeforeMiddleware and the ExampleAfterMiddleware. Now I see that the ExampleBeforeMiddleware is not correct, but anyway I mean the ExampleAfterMiddleware.

Here is a PSR-15 middleware example:

<?php

namespace App\Middleware;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Log\LoggerInterface;

final class HttpLoggerMiddleware implements MiddlewareInterface
{
    /**
     * @var LoggerInterface 
     */
    private $logger;

    public function __construct(LoggerInterface $logger)
    {
        $this->logger= $logger;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $response = $handler->handle($request);

        // Add logging here...
        $this->logger->info('Outgoing middleware example');

        return $response;
    }
}

Hello!

I’m not sure what goal you need to achieve, but perhaps you could to perform async actions using a queue message service like RabbitMQ.

So, when you receive a request, you can send an async message with your data to a queue, and then send the response immediately.

In the meantime, in parallel, another worker/consumer program is listening in this queue, and when you receive a new message you process the data, do some extra stuff and finish your work flow.

I share an example of the documentation in case it is helpful.

You can install and integrate the php-amqplib client library in Slim projects using composer.

Examples:

1 Like