概述 快速入门 教程 手册 最佳实践 组件 参考 贡献

发布于 2015-08-27 16:54:20 | 216 次阅读 | 评论: 0 | 来源: 网络整理

Symfony has various events and hooks that can be used to trigger custom behavior in your application. Those events are thrown by the HttpKernel component and can be viewed in the KernelEvents class.

To hook into an event and add your own custom logic, you have to create a service that will act as an event listener on that event. In this entry, you will create a service that will act as an Exception Listener, allowing you to modify how exceptions are shown by your application. The KernelEvents::EXCEPTION event is just one of the core kernel events:

// src/AppBundle/EventListener/AcmeExceptionListener.php
namespace AppBundleEventListener;

use SymfonyComponentHttpKernelEventGetResponseForExceptionEvent;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentHttpKernelExceptionHttpExceptionInterface;

class AcmeExceptionListener
{
    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        // You get the exception object from the received event
        $exception = $event->getException();
        $message = sprintf(
            'My Error says: %s with code: %s',
            $exception->getMessage(),
            $exception->getCode()
        );

        // Customize your response object to display the exception details
        $response = new Response();
        $response->setContent($message);

        // HttpExceptionInterface is a special type of exception that
        // holds status code and header details
        if ($exception instanceof HttpExceptionInterface) {
            $response->setStatusCode($exception->getStatusCode());
            $response->headers->replace($exception->getHeaders());
        } else {
            $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
        }

        // Send the modified response object to the event
        $event->setResponse($response);
    }
}

小技巧

Each event receives a slightly different type of $event object. For the kernel.exception event, it is GetResponseForExceptionEvent. To see what type of object each event listener receives, see KernelEvents.

注解

When setting a response for the kernel.request, kernel.view or kernel.exception events, the propagation is stopped, so the lower priority listeners on that event don’t get called.

Now that the class is created, you just need to register it as a service and notify Symfony that it is a “listener” on the kernel.exception event by using a special “tag”:

  • YAML
    # app/config/services.yml
    services:
        kernel.listener.your_listener_name:
            class: AppBundleEventListenerAcmeExceptionListener
            tags:
                - { name: kernel.event_listener, event: kernel.exception, method: onKernelException }
    
  • XML
    <!-- app/config/services.xml -->
    <service id="kernel.listener.your_listener_name" class="AppBundleEventListenerAcmeExceptionListener">
        <tag name="kernel.event_listener" event="kernel.exception" method="onKernelException" />
    </service>
    
  • PHP
    // app/config/services.php
    $container
        ->register('kernel.listener.your_listener_name', 'AppBundleEventListenerAcmeExceptionListener')
        ->addTag('kernel.event_listener', array('event' => 'kernel.exception', 'method' => 'onKernelException'))
    ;
    

注解

There is an additional tag option priority that is optional and defaults to 0. This value can be from -255 to 255, and the listeners will be executed in the order of their priority (highest to lowest). This is useful when you need to guarantee that one listener is executed before another.

Request Events, Checking Types

A single page can make several requests (one master request, and then multiple sub-requests), which is why when working with the KernelEvents::REQUEST event, you might need to check the type of the request. This can be easily done as follow:

// src/AppBundle/EventListener/AcmeRequestListener.php
namespace AppBundleEventListener;

use SymfonyComponentHttpKernelEventGetResponseEvent;
use SymfonyComponentHttpKernelHttpKernel;

class AcmeRequestListener
{
    public function onKernelRequest(GetResponseEvent $event)
    {
        if (!$event->isMasterRequest()) {
            // don't do anything if it's not the master request
            return;
        }

        // ...
    }
}

小技巧

Two types of request are available in the HttpKernelInterface interface: HttpKernelInterface::MASTER_REQUEST and HttpKernelInterface::SUB_REQUEST.

Debugging Event Listeners

2.6 新版功能: The debug:event-dispatcher command was introduced in Symfony 2.6.

You can find out what listeners are registered in the event dispatcher using the console. To show all events and their listeners, run:

$ php app/console debug:event-dispatcher

You can get registered listeners for a particular event by specifying its name:

$ php app/console debug:event-dispatcher kernel.exception
最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务