Symfony事件监听

  1. 作者QQ:67065435 QQ群:821635552

  2. 参考链接1

  3. 参考链接2

  4. 监听请求、响应示例

    1. 修改[项目路径]\src\ListenAllBundle\Resources\config\services.yml

      services:
          listen_all:
              class: ListenAllBundle\Service\ListenAll
              # 这里可以传递服务、普通数据、参数, 如不明白可看:【symfony:symfony服务】一节
              #arguments: ["@service_id", "plain_value", "%parameter%"]
              tags:
                  # name: 名字-监听, event:事件-请求, method:方法-Service方法名 priority: 优先级-0~255
                  - {name: kernel.event_listener, event: kernel.request, method: onKernelRequest, priority: 255}
                  # name: 名字-监听, event:事件-响应, method:方法-Service方法名 priority: 优先级-0~255
                  - {name: kernel.event_listener, event: kernel.response, method: onKernelResponse, priority: 254}
      
    2. 修改[项目路径]\src\ListenAllBundle\Service\ListenAll.php

      <?php
      
      namespace ListenAllBundle\Service;
      
      use Symfony\Component\HttpFoundation\Response;
      use Symfony\Component\HttpKernel\Event\GetResponseEvent;
      use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
      
      class ListenAll
      {
          /**
           * 请求时拒绝没有权限的用户访问
           */
          public function onKernelRequest(GetResponseEvent $event)
          {
              $request_method = $_SERVER['REQUEST_METHOD'];
              //在1=2条件下,Ajax请求直接被驳回
              if (1 === 2 && isset($_SERVER['HTTP_ORIGIN'])) {
                  $response = new Response();
                  $response->headers->set('Access-Control-Allow-Credentials', 'true');
                  $response->headers->set('Content-Type', "application/json;charset=UTF-8");
                  $response->headers->set('Access-Control-Allow-Origin', $_SERVER['HTTP_ORIGIN']);
                  $response->headers->set('Access-Control-Allow-Methods', 'POST,DELETE,PUT,GET,HEAD,PATCH,OPTIONS');
                  $response->setContent(json_encode(['code' => 403, 'data' =>[], 'msg' => 'Access denied.'], JSON_UNESCAPED_UNICODE));
                  $event->setResponse($response);
              }
          }
      
          /**
           * 响应时允许相同二级域名跨域
           */
          public function onKernelResponse(FilterResponseEvent $event)
          {
              $response = $event->getResponse();
              $host = $this->getParentDomain($_SERVER['HTTP_HOST']);
              if (isset($_SERVER['HTTP_ORIGIN'])) {
                  $origin = $this->getParentDomain($_SERVER['HTTP_ORIGIN']);
                  if ($host == $origin) {
                      $response->headers->set('Access-Control-Allow-Credentials', 'true');
                      $response->headers->set('Access-Control-Allow-Origin', $_SERVER['HTTP_ORIGIN']);
                      $response->headers->set('Access-Control-Allow-Methods', 'POST,DELETE,PUT,GET,HEAD,PATCH,OPTIONS');
                  }
              }
          }
      
          /**
           * 获取二级域名
           */
          private function getParentDomain(string $domain)
          {
              $domain = preg_replace('/^(.*)?:\/\//', '', $domain);
              $domain_arr = explode(':', $domain);
              $domain = $domain_arr[0];
              $is_ip = filter_var($domain, FILTER_VALIDATE_IP);
              if ($is_ip) {
                  return $domain;
              }
              $domain = trim($domain, '.');
              $domain_arr = explode('.', $domain);
              if (count($domain_arr) === 1) {
                  $domain = $domain_arr[0];
              } else {
                  array_shift($domain_arr);
                  $domain = implode('.', $domain_arr);
              }
              return $domain;
          }
      }
      
Copyright © 豆包嘿嘿~ 2012-∞ 冀ICP备17033181号 all right reserved,powered by Gitbook修订: 2012-12-31 12:00:00

results matching ""

    No results matching ""