Dependency injection in Symfony 3.4 : check existence of a service

995 views Asked by At

I am in the process of migrating an application from Symfony 2.8 to Symfony 3.4

The services are now private and therefore instead of making a direct call to the services from the container, we must use dependency injection as a workaround.

So this is the following script and i'd like to check the existence and after that call profiler service using dependency injection :

<?php

namespace DEL\Bundle\ApiBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Class EstimatePDFController
 *
 * @package DEL\Bundle\ApiBundle\Controller
 */
class EstimateController extends Controller
{
    /**
     *
     * @param Request $request Request object.
     *
     * @return Response A Response instance
     */
    public function sendAction(Request $request)
    {
        // disable debug env outputs
        if ($this->container->has('profiler')) {
            $this->container->get('profiler')->disable();
        }

        return new Response('OK');
    }
}
2

There are 2 answers

0
Nico Haase On BEST ANSWER

As far as I know, this is not possible using autowiring. But the documentation provides an alternative:

  • add the profiler to your controller as a property
  • add a setter like setProfiler(Profiler $profiler) that sets the property
  • add a conditional setter to your service definition:
    calls:
       - [setProfiler, ['@?profiler']]
    
  • check whether $this->profiler is null or not in your sendAction method
0
Nover On

Checking the existence means the Profiler exists before using it right? So you can autowire the Profiler with a default value and if it is not null, it exists. Something like this:

/**
 * @param Request  $request  Request object.
 * @param Profiler $profiler The Profiler if the service exists 
 *
 * @return Response A Response instance
 */
public function sendAction(Request $request, Profiler $profiler = null): Response
{
    // disable debug env outputs
    if ($profiler !== null) {
        $profiler->disable();
    }

    return new Response('OK');
}

This is the default behaviour by the way. It tries to resolve the argument, but if it fails, it skips it. And if you have no default value, then PHP fails.