Change Service Based on Debug Mode using Factory in Symfony 7

Change Service Based on Debug Mode using Factory in Symfony 7

For certain scenarios, employing the factory design pattern becomes necessary when creating an instance of a class. Sometimes, may be required to dynamically change services based on the application's debug mode. This technique allows replacing services with alternative implementations or configurations when debugging, providing a flexible way to adapt the application behavior to the development environment. This tutorial shows how to change service based on debug mode using factory in Symfony 7.

Within the .env file, it is possible to set the APP_ENV variable, determining the operational environment in which the application functions.

.env

APP_ENV=dev

Typically, debug mode is enabled in the dev and test environments, while it remains disabled in the prod environment.

Symfony offers a mechanism to utilize expressions as service factories. This can help in special cases such as changing the service based on a parameter.

The following example shows how to change the service based on the debug mode:

config/services.yaml

services:
    # ...

    App\Service\NotifierInterface:
        factory: '@=parameter("kernel.debug") ? service("App\\Service\\LoggingNotifier") : service("App\\Service\\Notifier")'

The LoggingNotifier service is used when debug mode is enabled, Notifier otherwise.

The following code can be used for testing:

src/Controller/TestController.php

<?php

namespace App\Controller;

use App\Service\NotifierInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class TestController
{
    #[Route('/')]
    public function index(NotifierInterface $notifier): Response
    {
        // If debug is enabled - Output: App\Service\Notifier
        // If debug is disabled - Output: App\Service\LoggingNotifier

        return new Response($notifier::class);
    }
}

src/Service/NotifierInterface.php

<?php

namespace App\Service;

interface NotifierInterface
{
}

src/Service/Notifier.php

<?php

namespace App\Service;

class Notifier implements NotifierInterface
{
}

src/Service/LoggingNotifier.php

<?php

namespace App\Service;

class LoggingNotifier implements NotifierInterface
{
}

Leave a Comment

Cancel reply

Your email address will not be published.