Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony run command from controller on the server

I want to clear the cache from the controller. I have defined the command as a service and call it.

clear_cache_command_service:
    class: Symfony\Bundle\FrameworkBundle\Command\CacheClearCommand
    calls:
       - [setContainer, ["@service_container"] ]

In my controller I have a form to choose a command, and when the cache-clearing command is chosen it runs:

    $clearCacheCommand = $this->container->get('clear_cache_command_service');
    $clearCacheCommand->run(new ArrayInput(array()), new ConsoleOutput());

This however runs for a while, since it also warms up the cache (I actually want it to also warm it up). It also times out so I need to set_time_limit it, too.

Is there a way to return a response in the browser and let the command run and finish on the server? I don't want the client to keep waiting for it to finish.

like image 404
George Irimiciuc Avatar asked Aug 11 '26 07:08

George Irimiciuc


2 Answers

Because of how php works - synchronously - it is not possible to do in a "classic" way in which you need to wait until command completes to terminate and send the response. Solution here is to incorporate worker pattern. You can find some useful info here. Basically you need to add "clear cache" task to queue and let other process handle this queue so in you case call clear cache command.

A common solution used in symfony in such cases is using RabbitMQ, there's a lot of resources about it:

Using in symfony

RabbitMQBundle

Let RabbitMQ Do The Work In Your Symfony2 Application

like image 195
Tomasz Madeyski Avatar answered Aug 13 '26 01:08

Tomasz Madeyski


For running command after response you have to use listener on kernel.terminate event. The purpose of this event is to perform tasks after the response was already served to the client.

// send the headers and echo the content
$response->send();

// triggers the kernel.terminate event
$kernel->terminate($request, $response);

Listener example

The kernel.terminate Event documentation

like image 25
Anna Adamchuk Avatar answered Aug 13 '26 01:08

Anna Adamchuk