Enabling the Symfony profiler conditionally

Published on 2020-04-12 • Modified on 2020-04-12

In this snippet, we will see how to enable or disable the Symfony profiler conditionally. I was reading the documentation (check out the "read the doc" link) then I realised it wasn't working. I tried to add that alias as the doc says, it works with the development environment but not with the production one. So, instead of adding this alias, I added a conditional named service in my services.yaml file:
$profiler: '@?profiler'
It is located in the services > _defaults > bind section. Now, it works in both environments. I have created an issue on the Symfony tracker so the documentation can be fixed (check the "more on the web" link). I find this solution very elegant 😊.


    #[Route(path: '/phpinfo', name: 'phpinfo')]
    public function phpInfoAction(Request $request, ?Profiler $profiler): Response
    {
        $profiler?->disable(); // PHP 8
        /* Before PHP 8
        if ($profiler !== null) {
            $profiler->disable(); // or ->enable()
        }
        */

 More on Stackoverflow   Read the doc  More on the web  Random snippet

  Work with me!