Cover of the book Symfony 5: The Fast Track

Symfony 5: The Fast Track is the best book to learn modern Symfony development, from zero to production. +300 pages showcasing Symfony with Docker, APIs, queues & async tasks, Webpack, SPAs, etc.

WARNING:

You are browsing the documentation for Symfony 4.1 which is not maintained anymore.

Consider upgrading your projects to Symfony 5.2.

How to Use Matchers to Enable the Profiler Conditionally

4.1 version
Unmaintained

How to Use Matchers to Enable the Profiler Conditionally

Caution

The possibility to use a matcher to enable the profiler conditionally was removed in Symfony 4.0.

Symfony Profiler cannot be enabled/disabled conditionally using matchers, because that feature was removed in Symfony 4.0. However, you can use the enable() and disable() methods of the Symfony\Component\HttpKernel\Profiler\Profiler class in your controllers to manage the profiler programmatically:

use Symfony\Component\HttpKernel\Profiler\Profiler;
// ...

class DefaultController
{
    // ...

    public function someMethod(?Profiler $profiler)
    {
        // $profiler won't be set if your environment doesn't have the profiler (like prod, by default)
        if (null !== $profiler) {
            // if it exists, disable the profiler for this particular controller action
            $profiler->disable();
        }

        // ...
    }
}

In order for the profiler to be injected into your controller you need to create an alias pointing to the existing profiler service:

  • YAML
    1
    2
    3
    # config/services_dev.yaml
    services:
        Symfony\Component\HttpKernel\Profiler\Profiler: '@profiler'
    
  • XML
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    <!-- config/services_dev.xml -->
    <?xml version="1.0" encoding="UTF-8" ?>
    <container xmlns="http://symfony.com/schema/dic/services"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://symfony.com/schema/dic/services
            http://symfony.com/schema/dic/services/services-1.0.xsd">
    
        <services>
            <service id="Symfony\Component\HttpKernel\Profiler\Profiler" alias="profiler" />
        </services>
    </container>
    
  • PHP
    1
    2
    3
    4
    // config/services_dev.php
    use Symfony\Component\HttpKernel\Profiler\Profiler;
    
    $container->setAlias(Profiler::class, 'profiler');
    

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.