Symfony back ground activity after to send response error session

Viewed 50

I'm using Symfony 4.4 with Redis for the session.

I have some controllers and I wish to update the DB on back ground after to send a reply to user.

So I have written a code like this:

class GetCatController extends AbstractController
{
    public function getCatController(LoggerInterface $logger, ManagerRegistry $doctrine, SessionInterface $session, ValidatorInterface $validator)
    {
       [...]
       $replyToSend =  new JsonResponse($reply, 200);
       $replyToSend->send();
       
      //My back ground activity like to do some query on the db.
        [...]

        return null;
    }

But I have some problems about the sessions.

Is there a better way to create and run background activity sending before the reply to user?

1 Answers

There are two decent ways to do this.

If you are running PHP under php-fpm (not mod_php), you can dispatch & catch an event, kernel.terminate In Symfony pre-4.4, this is called PostResponseEvent (TerminateEvent from 4.4/5.0).

The better choice may be with Symfony Messenger. Here, you would create a message object, with all the information needed to perform the task, and send it to a background queue (Redis is supported as a queue). A worker then consumes that message, and does the task.

Related