透过Symfony框架来创建一个站点维护模式很简单。只需在用户请求的时候检查站点是否处在维护模式中。当维护模式启动时,所有的请求都会被重新定向致某个页面去。
可以在EventListener的 onKernelRequest做到这一点:
1 <?php 2 3 namespace App\EventListener; 4 5 6 class MaintenanceListener 7 { 10 public function onKernelRequest(RequestEvent $event) 11 { 12 // 逻辑放这里 13 } 14 }
去 service.yaml 创建一个新的parameter,然后注册你的 MaintenanceListener:
parameters: maintenance: true services: App\EventListener\MaintenanceListener: tags: - { name: kernel.event_listener, event: kernel.request } arguments: $maintenance: ‘%maintenance%‘
maintenance 是维护模式的开关,绑定maintenance的值去 $maintenance变数,并把它带入 MaintenanceListener的 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(); } }
当网站收到用户请求时,会进入 onKernelRequest里并检查 maintenance 是否为 true。若maintenance为true,返回一个页面给用户,然后终止其它的event。
原文地址:https://www.cnblogs.com/novice-programmer/p/11609388.html
时间: 2024-10-03 09:38:32