Warning : Please notice this article is more than 1 year old. Some mechanics may have changed due to the newer versions of the used tools.
Developing a website is synonymous of multiple releases which can cause some undesirables critical errors.
In this tutorial, we will learn how to make a simple and efficient maintenance mode with Symfony.
Furthermore, you'll still be able to access your website while maintenance mode is active.
Let's go.
First of all, we need to define a new parameter with a boolean value you will use to toggle maintenance on or off.
Do the following in your parameters.yml
file :
#app/config/parameters.yml
parameters:
maintenance: false
Keep it to false for now.
Then, we will create the listener class that will detect if maintenance is enabled. We will name it MaintenanceListener.php
<?php
namespace AcmeBundle\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Response;
class MaintenanceListener
{
private $container;
public function __contruct(ContainerInterface $container)
{
$this->container = $container;
}
public function onKernelRequest(GetResponseEvent $event)
{
// This will get the value of our maintenance parameter
$maintenance = $this->container->hasParameter('maintenance') ? $this->container->getParameter('maintenance') : false;
// This will detect if we are in dev environment (app_dev.php)
$debug = in_array($this->container->get('kernel')->getEnvironment(), ['dev']);
// If maintenance is active and in prod environment
if ($maintenance && !$debug) {
// We load our maintenance template
$engine = $this->container->get('templating');
$template = $engine->render('::maintenance.html.twig');
// We send our response with a 503 response code (service unavailable)
$event->setResponse(new Response($template, 503));
$event->stopPropagation();
}
}
}
And now the service declaration :
#AcmeBundle/Resources/config/services.xml
<service id="acme.maintenance_mode" class="AcmeBundle\EventListener\MaintenanceListener">
<argument type="service" id="service_container" />
<tag name="kernel.event_listener" event="kernel.request" method="onKernelRequest" />
</service>
So we have now a MaintenanceListener class which will disable your website in a production environment if you set it to true. Cool isn't it ? 
Don't forget to create your own maintenance template in app/Resources/views/maintenance.html.twig
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Site temporarily under maintenance</title>
</head>
<body>
<h1>Site temporarily under maintenance</h1>
<p>Sorry for the inconvenience, we will get back soon !</p>
</body>
</html>
That's all folks, I hope this tutorial helped you ! :)
Do not hesitate to give me your feedback or asking some questions !
Hugo.