diff --git a/book/index.rst b/book/index.rst index 185f7ccb88f..70d6cd2558e 100644 --- a/book/index.rst +++ b/book/index.rst @@ -21,6 +21,5 @@ The Book translation service_container performance - internals .. include:: /book/map.rst.inc diff --git a/book/internals.rst b/book/internals.rst deleted file mode 100644 index 7a0db79fb61..00000000000 --- a/book/internals.rst +++ /dev/null @@ -1,668 +0,0 @@ -.. index:: - single: Internals - -Internals -========= - -Looks like you want to understand how Symfony works and how to extend it. -That makes me very happy! This section is an in-depth explanation of the -Symfony internals. - -.. note:: - - You only need to read this section if you want to understand how Symfony - works behind the scenes, or if you want to extend Symfony. - -Overview --------- - -The Symfony code is made of several independent layers. Each layer is built -on top of the previous one. - -.. tip:: - - Autoloading is not managed by the framework directly; it's done by using - Composer's autoloader (``vendor/autoload.php``), which is included in - the ``app/autoload.php`` file. - -HttpFoundation Component -~~~~~~~~~~~~~~~~~~~~~~~~ - -The deepest level is the :namespace:`Symfony\\Component\\HttpFoundation` -component. HttpFoundation provides the main objects needed to deal with HTTP. -It is an object-oriented abstraction of some native PHP functions and -variables: - -* The :class:`Symfony\\Component\\HttpFoundation\\Request` class abstracts - the main PHP global variables like ``$_GET``, ``$_POST``, ``$_COOKIE``, - ``$_FILES``, and ``$_SERVER``; - -* The :class:`Symfony\\Component\\HttpFoundation\\Response` class abstracts - some PHP functions like ``header()``, ``setcookie()``, and ``echo``; - -* The :class:`Symfony\\Component\\HttpFoundation\\Session\\Session` class and - :class:`Symfony\\Component\\HttpFoundation\\Session\\Storage\\SessionStorageInterface` - interface abstract session management ``session_*()`` functions. - -.. note:: - - Read more about the :doc:`HttpFoundation component `. - -HttpKernel Component -~~~~~~~~~~~~~~~~~~~~ - -On top of HttpFoundation is the :namespace:`Symfony\\Component\\HttpKernel` -component. HttpKernel handles the dynamic part of HTTP; it is a thin wrapper -on top of the Request and Response classes to standardize the way requests are -handled. It also provides extension points and tools that makes it the ideal -starting point to create a web framework without too much overhead. - -It also optionally adds configurability and extensibility, thanks to the -DependencyInjection component and a powerful plugin system (bundles). - -.. seealso:: - - Read more about the :doc:`HttpKernel component `, - :doc:`Dependency Injection ` and - :doc:`Bundles `. - -FrameworkBundle -~~~~~~~~~~~~~~~ - -The :namespace:`Symfony\\Bundle\\FrameworkBundle` bundle is the bundle that -ties the main components and libraries together to make a lightweight and fast -MVC framework. It comes with a sensible default configuration and conventions -to ease the learning curve. - -.. index:: - single: Internals; Kernel - -Kernel ------- - -The :class:`Symfony\\Component\\HttpKernel\\HttpKernel` class is the central -class of Symfony and is responsible for handling client requests. Its main -goal is to "convert" a :class:`Symfony\\Component\\HttpFoundation\\Request` -object to a :class:`Symfony\\Component\\HttpFoundation\\Response` object. - -Every Symfony Kernel implements -:class:`Symfony\\Component\\HttpKernel\\HttpKernelInterface`:: - - function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true) - -.. index:: - single: Internals; Controller resolver - -Controllers -~~~~~~~~~~~ - -To convert a Request to a Response, the Kernel relies on a "Controller". A -Controller can be any valid PHP callable. - -The Kernel delegates the selection of what Controller should be executed -to an implementation of -:class:`Symfony\\Component\\HttpKernel\\Controller\\ControllerResolverInterface`:: - - public function getController(Request $request); - - public function getArguments(Request $request, $controller); - -The -:method:`Symfony\\Component\\HttpKernel\\Controller\\ControllerResolverInterface::getController` -method returns the Controller (a PHP callable) associated with the given -Request. The default implementation -(:class:`Symfony\\Component\\HttpKernel\\Controller\\ControllerResolver`) -looks for a ``_controller`` request attribute that represents the controller -name (a "class::method" string, like ``Bundle\BlogBundle\PostController:indexAction``). - -.. tip:: - - The default implementation uses the - :class:`Symfony\\Bundle\\FrameworkBundle\\EventListener\\RouterListener` - to define the ``_controller`` Request attribute (see :ref:`kernel-core-request`). - -The -:method:`Symfony\\Component\\HttpKernel\\Controller\\ControllerResolverInterface::getArguments` -method returns an array of arguments to pass to the Controller callable. The -default implementation automatically resolves the method arguments, based on -the Request attributes. - -.. sidebar:: Matching Controller Method Arguments from Request Attributes - - For each method argument, Symfony tries to get the value of a Request - attribute with the same name. If it is not defined, the argument default - value is used if defined:: - - // Symfony will look for an 'id' attribute (mandatory) - // and an 'admin' one (optional) - public function showAction($id, $admin = true) - { - // ... - } - -.. index:: - single: Internals; Request handling - -Handling Requests -~~~~~~~~~~~~~~~~~ - -The :method:`Symfony\\Component\\HttpKernel\\HttpKernel::handle` method -takes a ``Request`` and *always* returns a ``Response``. To convert the -``Request``, ``handle()`` relies on the Resolver and an ordered chain of -Event notifications (see the next section for more information about each -Event): - -#. Before doing anything else, the ``kernel.request`` event is notified -- if - one of the listeners returns a ``Response``, it jumps to step 8 directly; - -#. The Resolver is called to determine the Controller to execute; - -#. Listeners of the ``kernel.controller`` event can now manipulate the - Controller callable the way they want (change it, wrap it, ...); - -#. The Kernel checks that the Controller is actually a valid PHP callable; - -#. The Resolver is called to determine the arguments to pass to the Controller; - -#. The Kernel calls the Controller; - -#. If the Controller does not return a ``Response``, listeners of the - ``kernel.view`` event can convert the Controller return value to a ``Response``; - -#. Listeners of the ``kernel.response`` event can manipulate the ``Response`` - (content and headers); - -#. The Response is returned; - -#. Listeners of the ``kernel.terminate`` event can perform tasks after the - Response has been served. - -If an exception is thrown during processing, the ``kernel.exception`` is -notified and listeners are given a chance to convert the exception into a -Response. If that works, the ``kernel.response`` event is notified; if not, the -Exception is re-thrown. - -If you don't want exceptions to be caught (for embedded requests for -instance), disable the ``kernel.exception`` event by passing ``false`` as the -third argument to the ``handle()`` method. - -.. index:: - single: Internals; Internal requests - -Internal Requests -~~~~~~~~~~~~~~~~~ - -At any time during the handling of a request (the 'master' one), a sub-request -can be handled. You can pass the request type to the ``handle()`` method (its -second argument): - -* ``HttpKernelInterface::MASTER_REQUEST``; -* ``HttpKernelInterface::SUB_REQUEST``. - -The type is passed to all events and listeners can act accordingly (some -processing must only occur on the master request). - -.. index:: - pair: Kernel; Event - -Events -~~~~~~ - -Each event thrown by the Kernel is a subclass of -:class:`Symfony\\Component\\HttpKernel\\Event\\KernelEvent`. This means that -each event has access to the same basic information: - -:method:`Symfony\\Component\\HttpKernel\\Event\\KernelEvent::getRequestType` - Returns the *type* of the request (``HttpKernelInterface::MASTER_REQUEST`` or - ``HttpKernelInterface::SUB_REQUEST``). - -:method:`Symfony\\Component\\HttpKernel\\Event\\KernelEvent::getKernel` - Returns the Kernel handling the request. - -:method:`Symfony\\Component\\HttpKernel\\Event\\KernelEvent::getRequest` - Returns the current ``Request`` being handled. - -``getRequestType()`` -.................... - -The ``getRequestType()`` method allows listeners to know the type of the -request. For instance, if a listener must only be active for master requests, -add the following code at the beginning of your listener method:: - - use Symfony\Component\HttpKernel\HttpKernelInterface; - - if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) { - // return immediately - return; - } - -.. tip:: - - If you are not yet familiar with the Symfony EventDispatcher component, - read :doc:`its documentation ` - section first. - -.. index:: - single: Event; kernel.request - -.. _kernel-core-request: - -``kernel.request`` Event -........................ - -*Event Class*: :class:`Symfony\\Component\\HttpKernel\\Event\\GetResponseEvent` - -The goal of this event is to either return a ``Response`` object immediately -or setup variables so that a Controller can be called after the event. Any -listener can return a ``Response`` object via the ``setResponse()`` method on -the event. In this case, all other listeners won't be called. - -This event is used by the FrameworkBundle to populate the ``_controller`` -``Request`` attribute, via the -:class:`Symfony\\Bundle\\FrameworkBundle\\EventListener\\RouterListener`. RequestListener -uses a :class:`Symfony\\Component\\Routing\\RouterInterface` object to match -the ``Request`` and determine the Controller name (stored in the -``_controller`` ``Request`` attribute). - -.. seealso:: - - Read more on the :ref:`kernel.request event `. - -.. index:: - single: Event; kernel.controller - -``kernel.controller`` Event -........................... - -*Event Class*: :class:`Symfony\\Component\\HttpKernel\\Event\\FilterControllerEvent` - -This event is not used by the FrameworkBundle, but can be an entry point used -to modify the controller that should be executed:: - - use Symfony\Component\HttpKernel\Event\FilterControllerEvent; - - public function onKernelController(FilterControllerEvent $event) - { - $controller = $event->getController(); - // ... - - // the controller can be changed to any PHP callable - $event->setController($controller); - } - -.. seealso:: - - Read more on the :ref:`kernel.controller event `. - -.. index:: - single: Event; kernel.view - -``kernel.view`` Event -..................... - -*Event Class*: :class:`Symfony\\Component\\HttpKernel\\Event\\GetResponseForControllerResultEvent` - -This event is not used by the FrameworkBundle, but it can be used to implement -a view sub-system. This event is called *only* if the Controller does *not* -return a ``Response`` object. The purpose of the event is to allow some other -return value to be converted into a ``Response``. - -The value returned by the Controller is accessible via the -``getControllerResult`` method:: - - use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent; - use Symfony\Component\HttpFoundation\Response; - - public function onKernelView(GetResponseForControllerResultEvent $event) - { - $val = $event->getControllerResult(); - $response = new Response(); - - // ... some how customize the Response from the return value - - $event->setResponse($response); - } - -.. seealso:: - - Read more on the :ref:`kernel.view event `. - -.. index:: - single: Event; kernel.response - -``kernel.response`` Event -......................... - -*Event Class*: :class:`Symfony\\Component\\HttpKernel\\Event\\FilterResponseEvent` - -The purpose of this event is to allow other systems to modify or replace the -``Response`` object after its creation:: - - public function onKernelResponse(FilterResponseEvent $event) - { - $response = $event->getResponse(); - - // ... modify the response object - } - -The FrameworkBundle registers several listeners: - -:class:`Symfony\\Component\\HttpKernel\\EventListener\\ProfilerListener` - Collects data for the current request. - -:class:`Symfony\\Bundle\\WebProfilerBundle\\EventListener\\WebDebugToolbarListener` - Injects the web debug toolbar. - -:class:`Symfony\\Component\\HttpKernel\\EventListener\\ResponseListener` - Fixes the Response ``Content-Type`` based on the request format. - -:class:`Symfony\\Component\\HttpKernel\\EventListener\\EsiListener` - Adds a ``Surrogate-Control`` HTTP header when the Response needs to be parsed - for ESI tags. - -.. seealso:: - - Read more on the :ref:`kernel.response event `. - -.. index:: - single: Event; kernel.terminate - -``kernel.terminate`` Event -.......................... - -*Event Class*: :class:`Symfony\\Component\\HttpKernel\\Event\\PostResponseEvent` - -The purpose of this event is to perform "heavier" tasks after the response -was already served to the client. - -.. seealso:: - - Read more on the :ref:`kernel.terminate event `. - -.. index:: - single: Event; kernel.exception - -.. _kernel-kernel.exception: - -``kernel.exception`` Event -.......................... - -*Event Class*: :class:`Symfony\\Component\\HttpKernel\\Event\\GetResponseForExceptionEvent` - -The FrameworkBundle registers an -:class:`Symfony\\Component\\HttpKernel\\EventListener\\ExceptionListener` that -forwards the ``Request`` to a given Controller (the value of the -``exception_listener.controller`` parameter -- must be in the -``class::method`` notation). - -A listener on this event can create and set a ``Response`` object, create -and set a new ``Exception`` object or do nothing:: - - use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent; - use Symfony\Component\HttpFoundation\Response; - - public function onKernelException(GetResponseForExceptionEvent $event) - { - $exception = $event->getException(); - $response = new Response(); - // setup the Response object based on the caught exception - $event->setResponse($response); - - // you can alternatively set a new Exception - // $exception = new \Exception('Some special exception'); - // $event->setException($exception); - } - -.. note:: - - As Symfony ensures that the Response status code is set to the most - appropriate one depending on the exception, setting the status on the - response won't work. If you want to overwrite the status code (which you - should not without a good reason), set the ``X-Status-Code`` header:: - - return new Response( - 'Error', - 404 // ignored, - array('X-Status-Code' => 200) - ); - -.. seealso:: - - Read more on the :ref:`kernel.exception event `. - -.. index:: - single: EventDispatcher - -.. _the-eventdispatcher: - -The EventDispatcher Component ------------------------------ - -The EventDispatcher is a standalone component that is responsible for much -of the underlying logic and flow behind a Symfony request. For more information, -see the :doc:`EventDispatcher component documentation `. - -.. index:: - single: Profiler - -.. _internals-profiler: - -Profiler --------- - -When enabled, the Symfony profiler collects useful information about each -request made to your application and store them for later analysis. Use the -profiler in the development environment to help you to debug your code and -enhance performance; use it in the production environment to explore problems -after the fact. - -You rarely have to deal with the profiler directly as Symfony provides -visualizer tools like the web debug toolbar and the web profiler. If you use -the Symfony Standard Edition, the profiler, the web debug toolbar, and the -web profiler are all already configured with sensible settings. - -.. note:: - - The profiler collects information for all requests (simple requests, - redirects, exceptions, Ajax requests, ESI requests; and for all HTTP - methods and all formats). It means that for a single URL, you can have - several associated profiling data (one per external request/response - pair). - -.. index:: - single: Profiler; Visualizing - -Visualizing Profiling Data -~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Using the Web Debug Toolbar -........................... - -In the development environment, the web debug toolbar is available at the -bottom of all pages. It displays a good summary of the profiling data that -gives you instant access to a lot of useful information when something does -not work as expected. - -If the summary provided by the web debug toolbar is not enough, click on the -token link (a string made of 13 random characters) to access the Web Profiler. - -.. note:: - - If the token is not clickable, it means that the profiler routes are not - registered (see below for configuration information). - -Analyzing Profiling Data with the Web Profiler -.............................................. - -The Web Profiler is a visualization tool for profiling data that you can use -in development to debug your code and enhance performance; but it can also be -used to explore problems that occur in production. It exposes all information -collected by the profiler in a web interface. - -.. index:: - single: Profiler; Using the profiler service - -Accessing the Profiling information -................................... - -You don't need to use the default visualizer to access the profiling -information. But how can you retrieve profiling information for a specific -request after the fact? When the profiler stores data about a Request, it also -associates a token with it; this token is available in the ``X-Debug-Token`` -HTTP header of the Response:: - - $profile = $container->get('profiler')->loadProfileFromResponse($response); - - $profile = $container->get('profiler')->loadProfile($token); - -.. tip:: - - When the profiler is enabled but not the web debug toolbar, or when you - want to get the token for an Ajax request, use a tool like Firebug to get - the value of the ``X-Debug-Token`` HTTP header. - -Use the :method:`Symfony\\Component\\HttpKernel\\Profiler\\Profiler::find` -method to access tokens based on some criteria:: - - // get the latest 10 tokens - $tokens = $container->get('profiler')->find('', '', 10, '', ''); - - // get the latest 10 tokens for all URL containing /admin/ - $tokens = $container->get('profiler')->find('', '/admin/', 10, '', ''); - - // get the latest 10 tokens for local requests - $tokens = $container->get('profiler')->find('127.0.0.1', '', 10, '', ''); - - // get the latest 10 tokens for requests that happened between 2 and 4 days ago - $tokens = $container->get('profiler') - ->find('', '', 10, '4 days ago', '2 days ago'); - -If you want to manipulate profiling data on a different machine than the one -where the information were generated, use the -:method:`Symfony\\Component\\HttpKernel\\Profiler\\Profiler::export` and -:method:`Symfony\\Component\\HttpKernel\\Profiler\\Profiler::import` methods:: - - // on the production machine - $profile = $container->get('profiler')->loadProfile($token); - $data = $profiler->export($profile); - - // on the development machine - $profiler->import($data); - -.. index:: - single: Profiler; Visualizing - -Configuration -............. - -The default Symfony configuration comes with sensible settings for the -profiler, the web debug toolbar, and the web profiler. Here is for instance -the configuration for the development environment: - -.. configuration-block:: - - .. code-block:: yaml - - # load the profiler - framework: - profiler: { only_exceptions: false } - - # enable the web profiler - web_profiler: - toolbar: true - intercept_redirects: true - - .. code-block:: xml - - - - - - - - - - - - - - .. code-block:: php - - // load the profiler - $container->loadFromExtension('framework', array( - 'profiler' => array('only_exceptions' => false), - )); - - // enable the web profiler - $container->loadFromExtension('web_profiler', array( - 'toolbar' => true, - 'intercept_redirects' => true, - )); - -When ``only_exceptions`` is set to ``true``, the profiler only collects data -when an exception is thrown by the application. - -When ``intercept_redirects`` is set to ``true``, the web profiler intercepts -the redirects and gives you the opportunity to look at the collected data -before following the redirect. - -If you enable the web profiler, you also need to mount the profiler routes: - -.. configuration-block:: - - .. code-block:: yaml - - _profiler: - resource: "@WebProfilerBundle/Resources/config/routing/profiler.xml" - prefix: /_profiler - - .. code-block:: xml - - - - - - - - .. code-block:: php - - use Symfony\Component\Routing\RouteCollection; - - $profiler = $loader->import( - '@WebProfilerBundle/Resources/config/routing/profiler.xml' - ); - $profiler->addPrefix('/_profiler'); - - $collection = new RouteCollection(); - $collection->addCollection($profiler); - -As the profiler adds some overhead, you might want to enable it only under -certain circumstances in the production environment. The ``only_exceptions`` -settings limits profiling to exceptions, but what if you want to get -information when the client IP comes from a specific address, or for a limited -portion of the website? You can use a Profiler Matcher, learn more about that -in ":doc:`/cookbook/profiler/matchers`". - -Learn more from the Cookbook ----------------------------- - -* :doc:`/cookbook/testing/profiling` -* :doc:`/cookbook/profiler/data_collector` -* :doc:`/cookbook/event_dispatcher/class_extension` -* :doc:`/cookbook/event_dispatcher/method_behavior` diff --git a/book/map.rst.inc b/book/map.rst.inc index 0a1b3381c09..d432bfe3674 100644 --- a/book/map.rst.inc +++ b/book/map.rst.inc @@ -15,4 +15,3 @@ * :doc:`/book/translation` * :doc:`/book/service_container` * :doc:`/book/performance` -* :doc:`/book/internals` diff --git a/cookbook/email/testing.rst b/cookbook/email/testing.rst index c95ea6cb5dc..3797f81b582 100644 --- a/cookbook/email/testing.rst +++ b/cookbook/email/testing.rst @@ -8,7 +8,7 @@ Sending emails with Symfony is pretty straightforward thanks to the SwiftmailerBundle, which leverages the power of the `Swift Mailer`_ library. To functionally test that an email was sent, and even assert the email subject, -content or any other headers, you can use :ref:`the Symfony Profiler `. +content or any other headers, you can use :doc:`the Symfony Profiler `. Start with an easy controller action that sends an email:: diff --git a/cookbook/map.rst.inc b/cookbook/map.rst.inc index 6c8e5d59d89..01c63dfa6cf 100644 --- a/cookbook/map.rst.inc +++ b/cookbook/map.rst.inc @@ -119,6 +119,7 @@ * :doc:`/cookbook/profiler/data_collector` * :doc:`/cookbook/profiler/matchers` * :doc:`/cookbook/profiler/storage` + * :doc:`/cookbook/profiler/profiling_data` * :doc:`/cookbook/request/index` diff --git a/cookbook/profiler/data_collector.rst b/cookbook/profiler/data_collector.rst index db3a86bfdab..cc0e0b6fea2 100644 --- a/cookbook/profiler/data_collector.rst +++ b/cookbook/profiler/data_collector.rst @@ -4,7 +4,7 @@ How to Create a custom Data Collector ===================================== -The Symfony :ref:`Profiler ` delegates data collecting to +:doc:`The Symfony Profiler ` delegates data collecting to data collectors. Symfony comes bundled with a few of them, but you can easily create your own. diff --git a/cookbook/profiler/index.rst b/cookbook/profiler/index.rst index 7ff3abe1982..b5fb1091099 100644 --- a/cookbook/profiler/index.rst +++ b/cookbook/profiler/index.rst @@ -7,3 +7,4 @@ Profiler data_collector matchers storage + profiling_data diff --git a/cookbook/profiler/profiling_data.rst b/cookbook/profiler/profiling_data.rst new file mode 100644 index 00000000000..fd5937f51e3 --- /dev/null +++ b/cookbook/profiler/profiling_data.rst @@ -0,0 +1,62 @@ +.. index:: + single: Profiling; Profiling data + +How to Access Profiling Data Programmatically +============================================= + +Most of the times, the profiler information is accessed and analyzed using its +web-based visualizer. However, you can also retrieve profiling information +programmatically thanks to the methods provided by the ``profiler`` service. + +When the response object is available, use the +:method:`Symfony\\Component\\HttpKernel\\Profiler\\Profiler::loadProfileFromResponse` +method to access to its associated profile:: + + // ... $profiler is the 'profiler' service + $profile = $profiler->loadProfileFromResponse($response); + +When the profiler stores data about a request, it also associates a token with it; +this token is available in the ``X-Debug-Token`` HTTP header of the response. +Using this token, you can access the profile of any past response thanks to the +:method:`Symfony\\Component\\HttpKernel\\Profiler\\Profiler::loadProfile` method:: + + $token = $request->headers->get('X-Debug-Token'); + $profile = $container->get('profiler')->loadProfile($token); + +.. tip:: + + When the profiler is enabled but not the web debug toolbar, inspect the page + with your browser's developer tools to get the value of the ``X-Debug-Token`` + HTTP header. + +The ``profiler`` service also provides the +:method:`Symfony\\Component\\HttpKernel\\Profiler\\Profiler::find` method to +look for tokens based on some criteria:: + + // get the latest 10 tokens + $tokens = $container->get('profiler')->find('', '', 10, '', ''); + + // get the latest 10 tokens for all URL containing /admin/ + $tokens = $container->get('profiler')->find('', '/admin/', 10, '', ''); + + // get the latest 10 tokens for local requests + $tokens = $container->get('profiler')->find('127.0.0.1', '', 10, '', ''); + + // get the latest 10 tokens for requests that happened between 2 and 4 days ago + $tokens = $container->get('profiler') + ->find('', '', 10, '4 days ago', '2 days ago'); + +Lastly, if you want to manipulate profiling data on a different machine than the +one where the information was generated, use the ``profiler:export`` and +``profiler:import`` commands: + +.. code-block:: bash + + # on the production machine + $ php app/console profiler:export > profile.data + + # on the development machine + $ php app/console profiler:import /path/to/profile.data + + # you can also pipe from the STDIN + $ cat /path/to/profile.data | php app/console profiler:import diff --git a/cookbook/testing/profiling.rst b/cookbook/testing/profiling.rst index 0f822cc2079..1789c69dbc9 100644 --- a/cookbook/testing/profiling.rst +++ b/cookbook/testing/profiling.rst @@ -9,7 +9,7 @@ you write functional tests that monitor your production servers, you might want to write tests on the profiling data as it gives you a great way to check various things and enforce some metrics. -The Symfony :ref:`Profiler ` gathers a lot of data for +:doc:`The Symfony Profiler ` gathers a lot of data for each request. Use this data to check the number of database calls, the time spent in the framework, etc. But before writing assertions, enable the profiler and check that the profiler is indeed available (it is enabled by default in diff --git a/glossary.rst b/glossary.rst index 07f3eeb44a4..87c53f4e9ba 100644 --- a/glossary.rst +++ b/glossary.rst @@ -110,7 +110,7 @@ Glossary The *Kernel* is the core of Symfony. The Kernel object handles HTTP requests using all the bundles and libraries registered to it. See :ref:`The Architecture: The Application Directory ` and the - :doc:`/book/internals` chapter. + :doc:`Internal Events Reference `. Firewall In Symfony, a *Firewall* doesn't have to do with networking. Instead, diff --git a/redirection_map b/redirection_map index 2d782f924fb..e2f84707c66 100644 --- a/redirection_map +++ b/redirection_map @@ -1,4 +1,5 @@ /book/stable_api /contributing/code/bc +/book/internals /reference/events /cookbook/deployment-tools /cookbook/deployment/tools /cookbook/doctrine/migrations /bundles/DoctrineFixturesBundle/index /cookbook/doctrine/doctrine_fixtures /bundles/DoctrineFixturesBundle/index diff --git a/reference/dic_tags.rst b/reference/dic_tags.rst index 7e4c467849d..993d7ad80e0 100644 --- a/reference/dic_tags.rst +++ b/reference/dic_tags.rst @@ -132,7 +132,7 @@ And then register it as a tagged service: xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> - @@ -549,86 +549,8 @@ cookbook entry. For another practical example of a kernel listener, see the cookbook article: :doc:`/cookbook/request/mime_type`. -Core Event Listener Reference -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -When adding your own listeners, it might be useful to know about the other -core Symfony listeners and their priorities. - -.. note:: - - All listeners listed here may not be listening depending on your environment, - settings and bundles. Additionally, third-party bundles will bring in - additional listeners not listed here. - -kernel.request -.............. - -+-------------------------------------------------------------------------------------------+-----------+ -| Listener Class Name | Priority | -+===========================================================================================+===========+ -| :class:`Symfony\\Component\\HttpKernel\\EventListener\\ProfilerListener` | 1024 | -+-------------------------------------------------------------------------------------------+-----------+ -| :class:`Symfony\\Bundle\\FrameworkBundle\\EventListener\\TestSessionListener` | 192 | -+-------------------------------------------------------------------------------------------+-----------+ -| :class:`Symfony\\Bundle\\FrameworkBundle\\EventListener\\SessionListener` | 128 | -+-------------------------------------------------------------------------------------------+-----------+ -| :class:`Symfony\\Component\\HttpKernel\\EventListener\\RouterListener` | 32 | -+-------------------------------------------------------------------------------------------+-----------+ -| :class:`Symfony\\Component\\HttpKernel\\EventListener\\LocaleListener` | 16 | -+-------------------------------------------------------------------------------------------+-----------+ -| :class:`Symfony\\Component\\Security\\Http\\Firewall` | 8 | -+-------------------------------------------------------------------------------------------+-----------+ - -kernel.controller -................. - -+-------------------------------------------------------------------------------------------+----------+ -| Listener Class Name | Priority | -+===========================================================================================+==========+ -| :class:`Symfony\\Bundle\\FrameworkBundle\\DataCollector\\RequestDataCollector` | 0 | -+-------------------------------------------------------------------------------------------+----------+ - -kernel.response -............... - -+-------------------------------------------------------------------------------------------+----------+ -| Listener Class Name | Priority | -+===========================================================================================+==========+ -| :class:`Symfony\\Component\\HttpKernel\\EventListener\\EsiListener` | 0 | -+-------------------------------------------------------------------------------------------+----------+ -| :class:`Symfony\\Component\\HttpKernel\\EventListener\\ResponseListener` | 0 | -+-------------------------------------------------------------------------------------------+----------+ -| :class:`Symfony\\Bundle\\SecurityBundle\\EventListener\\ResponseListener` | 0 | -+-------------------------------------------------------------------------------------------+----------+ -| :class:`Symfony\\Component\\HttpKernel\\EventListener\\ProfilerListener` | -100 | -+-------------------------------------------------------------------------------------------+----------+ -| :class:`Symfony\\Bundle\\FrameworkBundle\\EventListener\\TestSessionListener` | -128 | -+-------------------------------------------------------------------------------------------+----------+ -| :class:`Symfony\\Bundle\\WebProfilerBundle\\EventListener\\WebDebugToolbarListener` | -128 | -+-------------------------------------------------------------------------------------------+----------+ -| :class:`Symfony\\Component\\HttpKernel\\EventListener\\StreamedResponseListener` | -1024 | -+-------------------------------------------------------------------------------------------+----------+ - -kernel.exception -................ - -+-------------------------------------------------------------------------------------------+----------+ -| Listener Class Name | Priority | -+===========================================================================================+==========+ -| :class:`Symfony\\Component\\HttpKernel\\EventListener\\ProfilerListener` | 0 | -+-------------------------------------------------------------------------------------------+----------+ -| :class:`Symfony\\Component\\HttpKernel\\EventListener\\ExceptionListener` | -128 | -+-------------------------------------------------------------------------------------------+----------+ - -kernel.terminate -................ - -+-------------------------------------------------------------------------------------------+----------+ -| Listener Class Name | Priority | -+===========================================================================================+==========+ -| `EmailSenderListener`_ | 0 | -+-------------------------------------------------------------------------------------------+----------+ +For the reference of Event Listeners associated with each kernel event, see the +:doc:`Symfony Events Reference `. .. _dic-tags-kernel-event-subscriber: @@ -1423,4 +1345,3 @@ Bridge. .. _`Twig official extension repository`: https://github.com/twigphp/Twig-extensions .. _`SwiftMailer's Plugin Documentation`: http://swiftmailer.org/docs/plugins.html .. _`Twig Loader`: http://twig.sensiolabs.org/doc/api.html#loaders -.. _`EmailSenderListener`: https://github.com/symfony/SwiftmailerBundle/blob/master/EventListener/EmailSenderListener.php diff --git a/reference/events.rst b/reference/events.rst new file mode 100644 index 00000000000..f60c566380a --- /dev/null +++ b/reference/events.rst @@ -0,0 +1,241 @@ +Symfony Framework Events +======================== + +Kernel Events +------------- + +Each event dispatched by the kernel is a subclass of +:class:`Symfony\\Component\\HttpKernel\\Event\\KernelEvent`. This means that +each event has access to the following information: + +:method:`Symfony\\Component\\HttpKernel\\Event\\KernelEvent::getRequestType` + Returns the *type* of the request (``HttpKernelInterface::MASTER_REQUEST`` or + ``HttpKernelInterface::SUB_REQUEST``). + +:method:`Symfony\\Component\\HttpKernel\\Event\\KernelEvent::getKernel` + Returns the Kernel handling the request. + +:method:`Symfony\\Component\\HttpKernel\\Event\\KernelEvent::getRequest` + Returns the current ``Request`` being handled. + +.. _kernel-core-request: + +``kernel.request`` +~~~~~~~~~~~~~~~~~~ + +**Event Class**: :class:`Symfony\\Component\\HttpKernel\\Event\\GetResponseEvent` + +The goal of this event is to either return a ``Response`` object immediately +or setup variables so that a Controller can be called after the event. Any +listener can return a ``Response`` object via the ``setResponse()`` method on +the event. In this case, all other listeners won't be called. + +This event is used by the FrameworkBundle to populate the ``_controller`` +``Request`` attribute, via the +:class:`Symfony\\Bundle\\FrameworkBundle\\EventListener\\RouterListener`. +RequestListener uses a :class:`Symfony\\Component\\Routing\\RouterInterface` +object to match the ``Request`` and determine the Controller name (stored in the +``_controller`` ``Request`` attribute). + +.. seealso:: + + Read more on the :ref:`kernel.request event `. + +These are the built-in Symfony listeners registered to this event: + +============================================================================= ======== +Listener Class Name Priority +============================================================================= ======== +:class:`Symfony\\Component\\HttpKernel\\EventListener\\ProfilerListener` 1024 +:class:`Symfony\\Bundle\\FrameworkBundle\\EventListener\\TestSessionListener` 192 +:class:`Symfony\\Bundle\\FrameworkBundle\\EventListener\\SessionListener` 128 +:class:`Symfony\\Component\\HttpKernel\\EventListener\\RouterListener` 32 +:class:`Symfony\\Component\\HttpKernel\\EventListener\\LocaleListener` 16 +:class:`Symfony\\Component\\Security\\Http\\Firewall` 8 +============================================================================= ======== + +``kernel.controller`` +~~~~~~~~~~~~~~~~~~~~~ + +**Event Class**: :class:`Symfony\\Component\\HttpKernel\\Event\\FilterControllerEvent` + +This event can be an entry point used to modify the controller that should be executed:: + + use Symfony\Component\HttpKernel\Event\FilterControllerEvent; + + public function onKernelController(FilterControllerEvent $event) + { + $controller = $event->getController(); + // ... + + // the controller can be changed to any PHP callable + $event->setController($controller); + } + +.. seealso:: + + Read more on the :ref:`kernel.controller event `. + +This is the built-in Symfony listener related to this event: + +============================================================================== ======== +Listener Class Name Priority +============================================================================== ======== +:class:`Symfony\\Bundle\\FrameworkBundle\\DataCollector\\RequestDataCollector` 0 +============================================================================== ======== + +``kernel.view`` +~~~~~~~~~~~~~~~ + +**Event Class**: :class:`Symfony\\Component\\HttpKernel\\Event\\GetResponseForControllerResultEvent` + +This event is not used by the FrameworkBundle, but it can be used to implement +a view sub-system. This event is called *only* if the Controller does *not* +return a ``Response`` object. The purpose of the event is to allow some other +return value to be converted into a ``Response``. + +The value returned by the Controller is accessible via the ``getControllerResult`` +method:: + + use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent; + use Symfony\Component\HttpFoundation\Response; + + public function onKernelView(GetResponseForControllerResultEvent $event) + { + $val = $event->getControllerResult(); + $response = new Response(); + + // ... somehow customize the Response from the return value + + $event->setResponse($response); + } + +.. seealso:: + + Read more on the :ref:`kernel.view event `. + +``kernel.response`` +~~~~~~~~~~~~~~~~~~~ + +**Event Class**: :class:`Symfony\\Component\\HttpKernel\\Event\\FilterResponseEvent` + +The purpose of this event is to allow other systems to modify or replace the +``Response`` object after its creation:: + + public function onKernelResponse(FilterResponseEvent $event) + { + $response = $event->getResponse(); + + // ... modify the response object + } + +The FrameworkBundle registers several listeners: + +:class:`Symfony\\Component\\HttpKernel\\EventListener\\ProfilerListener` + Collects data for the current request. + +:class:`Symfony\\Bundle\\WebProfilerBundle\\EventListener\\WebDebugToolbarListener` + Injects the Web Debug Toolbar. + +:class:`Symfony\\Component\\HttpKernel\\EventListener\\ResponseListener` + Fixes the Response ``Content-Type`` based on the request format. + +:class:`Symfony\\Component\\HttpKernel\\EventListener\\EsiListener` + Adds a ``Surrogate-Control`` HTTP header when the Response needs to be parsed + for ESI tags. + +.. seealso:: + + Read more on the :ref:`kernel.response event `. + +These are the built-in Symfony listeners registered to this event: + +=================================================================================== ======== +Listener Class Name Priority +=================================================================================== ======== +:class:`Symfony\\Component\\HttpKernel\\EventListener\\EsiListener` 0 +:class:`Symfony\\Component\\HttpKernel\\EventListener\\ResponseListener` 0 +:class:`Symfony\\Bundle\\SecurityBundle\\EventListener\\ResponseListener` 0 +:class:`Symfony\\Component\\HttpKernel\\EventListener\\ProfilerListener` -100 +:class:`Symfony\\Bundle\\FrameworkBundle\\EventListener\\TestSessionListener` -128 +:class:`Symfony\\Bundle\\WebProfilerBundle\\EventListener\\WebDebugToolbarListener` -128 +:class:`Symfony\\Component\\HttpKernel\\EventListener\\StreamedResponseListener` -1024 +=================================================================================== ======== + +``kernel.terminate`` +~~~~~~~~~~~~~~~~~~~~ + +**Event Class**: :class:`Symfony\\Component\\HttpKernel\\Event\\PostResponseEvent` + +The purpose of this event is to perform tasks after the response was already +served to the client. + +.. seealso:: + + Read more on the :ref:`kernel.terminate event `. + +This is the built-in Symfony listener related to this event: + +========================================================================= ======== +Listener Class Name Priority +========================================================================= ======== +`EmailSenderListener`_ 0 +========================================================================= ======== + + +.. _kernel-kernel.exception: + +``kernel.exception`` +~~~~~~~~~~~~~~~~~~~~ + +**Event Class**: :class:`Symfony\\Component\\HttpKernel\\Event\\GetResponseForExceptionEvent` + +The TwigBundle registers an :class:`Symfony\\Component\\HttpKernel\\EventListener\\ExceptionListener` +that forwards the ``Request`` to a given controller defined by the +``exception_listener.controller`` parameter. + +A listener on this event can create and set a ``Response`` object, create +and set a new ``Exception`` object, or do nothing:: + + use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent; + use Symfony\Component\HttpFoundation\Response; + + public function onKernelException(GetResponseForExceptionEvent $event) + { + $exception = $event->getException(); + $response = new Response(); + // setup the Response object based on the caught exception + $event->setResponse($response); + + // you can alternatively set a new Exception + // $exception = new \Exception('Some special exception'); + // $event->setException($exception); + } + +.. note:: + + As Symfony ensures that the Response status code is set to the most + appropriate one depending on the exception, setting the status on the + response won't work. If you want to overwrite the status code (which you + should not without a good reason), set the ``X-Status-Code`` header:: + + return new Response( + 'Error', + 404 // ignored, + array('X-Status-Code' => 200) + ); + +.. seealso:: + + Read more on the :ref:`kernel.exception event `. + +These are the built-in Symfony listeners registered to this event: + +========================================================================= ======== +Listener Class Name Priority +========================================================================= ======== +:class:`Symfony\\Component\\HttpKernel\\EventListener\\ProfilerListener` 0 +:class:`Symfony\\Component\\HttpKernel\\EventListener\\ExceptionListener` -128 +========================================================================= ======== + +.. _`EmailSenderListener`: https://github.com/symfony/SwiftmailerBundle/blob/master/EventListener/EmailSenderListener.php diff --git a/reference/index.rst b/reference/index.rst index c5143e58f53..9d07c4c4609 100644 --- a/reference/index.rst +++ b/reference/index.rst @@ -22,6 +22,7 @@ Reference Documents twig_reference dic_tags + events requirements .. include:: /reference/map.rst.inc diff --git a/reference/map.rst.inc b/reference/map.rst.inc index 1b3ed361694..0bf22aa3b44 100644 --- a/reference/map.rst.inc +++ b/reference/map.rst.inc @@ -27,4 +27,5 @@ * **Other Areas** * :doc:`/reference/dic_tags` + * :doc:`/reference/events` * :doc:`/reference/requirements`