[Symfony 4.3] to create a site maintenance mode

To create a site through the Symfony framework maintenance mode is very simple. Just when requested by the user to check whether the site is in maintenance mode. When the maintenance mode is activated, all requests will be redirected to a page caused.

 

This can be done in onKernelRequest EventListener of:

 

. 1 ? < PHP
 2  
. 3  namespace the App \ EventListener A;
 . 4  
. 5  
. 6  class MaintenanceListener
 . 7  { 
10      public  function onKernelRequest (the RequestEvent $ Event )
 . 11      {
 12 is        // logic put here 
13      }
 14 }

 

Service.yaml to create a new parameter, then register your MaintenanceListener:

parameters:
    maintenance: true


services:

        App\EventListener\MaintenanceListener:
        tags:
            - { name: kernel.event_listener, event: kernel.request }
        arguments:
            $maintenance: '%maintenance%' 

 

maintenance is the maintenance mode switch, the maintenance of the value binding to $ maintenance variables, and put it into MaintenanceListener inside the constructor:

 

<?php

namespace App\EventListener;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Twig\Environment;

class MaintenanceListener
{
    private $maintenance;
    private $twig;

    public function __construct($maintenance, Environment $twig)
    {
        $this->maintenance = $maintenance;
        $this->twig = $twig;
    }

    public function onKernelRequest(RequestEvent $event)
    {
        
        if($this->maintenance != true)
        {
            return;
        }

        $event->setResponse(new Response($this->twig->render('maintenance.html.twig'), Response::HTTP_SERVICE_UNAVAILABLE));
        $event->stopPropagation();
    }
}

 

When a site receives a user request, it will enter onKernelRequest in and check whether maintenance is true. When maintenance is true, it returns a page to the user, and then terminates the other event.

 

Guess you like

Origin www.cnblogs.com/novice-programmer/p/11609388.html