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("/phpinfo", name="phpinfo")
    public function phpInfoAction(Request $request, ?Profiler $profiler): Response
        if ($profiler !== null) {
            $profiler->disable(); // or ->enable()
        $str = ob_get_contents();
        $ipInfo = sprintf('<h1>IP as seen by Symfony: %s</h1>', $request->getClientIp() ?? '');
        $str = str_replace('<body>', '<body>'.$ipInfo, (string) $str);

        return new Response($str);

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