Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Website under maintenance' page in Symfony2 [closed]

Tags:

php

symfony

How can I implement a 'website under maintenance' page easely and clearly in a Symfony2 web app?

I have found something about this for Symfony 1 but nothing for Symfony2.

Thanks.

like image 670
svprdga Avatar asked Jan 07 '14 12:01

svprdga


1 Answers

I followed this tutorial. It is very easy and straight forward. This was exaclty what i needed. You only have to change a parameter and then clear the prod cache and you are still able to access the application in dev or test environment.

In your parameters.yml add this:

parameters:
    maintenance: false #turn it to true to enable maintenance
    underMaintenanceUntil: tomorrow 8 AM

Then you define a Service:

services:
    acme.listener.maintenance:
        class: Acme\DemoBundle\Listener\MaintenanceListener
        arguments:
            container: "@service_container"
        tags:
            - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }

And finally the event listener:

<?php

namespace Acme\DemoBundle\Listener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\DependencyInjection\ContainerInterface;

class MaintenanceListener
{
    private $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        $maintenanceUntil = $this->container->hasParameter('underMaintenanceUntil') ? $this->container->getParameter('underMaintenanceUntil') : false;
        $maintenance = $this->container->hasParameter('maintenance') ? $this->container->getParameter('maintenance') : false;

        $debug = in_array($this->container->get('kernel')->getEnvironment(), array('test', 'dev'));

        if ($maintenance && !$debug) {
            $engine = $this->container->get('templating');
            $content = $engine->render('::maintenance.html.twig', array('maintenanceUntil'=>$maintenanceUntil));
            $event->setResponse(new Response($content, 503));
            $event->stopPropagation();
        }

    }
}

Then you just have to add the template file referenced in $content = $engine->render('::maintenance.html.twig', array('maintenanceUntil'=>$maintenanceUntil)); and your fine. Use {{ maintenanceUntil }} to display the message defined in parameters.yml.

like image 80
Markus Kottländer Avatar answered Sep 26 '22 13:09

Markus Kottländer