Dependency Injection in practice: changing the notification method without changing the use case

One contract, two local adapters and an explicit Symfony alias: change how a notification is recorded, preserve the use case and check it with a recording double.

Two different modules beside one socket: a conceptual metaphor for replacing a dependency through a shared contract.
Two different modules beside one socket: a conceptual metaphor for replacing a dependency through a shared contract.

Imagine a small teaching application: an author prepares a note and wants to leave a message saying it is ready. Initially, a plain text file is enough. Later, the requirement becomes JSONL: each message is a separate JSON object that another program can read more easily. The rule for announcing the note stays the same. The way the message is recorded changes.

If the use case creates the file adapter itself, it must change along with that decision. If it receives a ready dependency, the place that needs to change can move into configuration. This is the distinction I want to show through one complete Dependency Injection example: a contract, two adapters, selection in the container, and a test double that records calls.

Both adapters here are local. They model different notification methods by writing files, without sending email or contacting external services. Success means the local write operation completed without an exception. It does not mean a person received or read the message. The example does not create a note in a database either: its only task is to announce the supplied title.

Which change are we isolating?

“Independent sites with a shared Symfony foundation” discussed the boundary between a shared technical capability and a product decision. Here, the boundary lies inside one application: the use case knows the message content, the adapter knows how to record it, and configuration chooses the implementation.

One interface, Notifier, is enough for this. The AnnounceNote use case and the command will not have separate interfaces. We have a specific dependency that can change, so the abstraction serves an actual need. It is not being introduced simply because of a rule that “every class needs a partner”.

Part Its decision
AnnounceNote Accept the title, validate input, prepare the message
Notifier Define the call and the meaning of completion or failure
File adapter Turn the message into a local record
Symfony configuration Choose the implementation for the Notifier argument
Console command Accept an argument and return a clear process result

The replacement happens through configuration: one adapter is selected for all calls to this use case in a given environment. This is not a user choosing a channel during a request. When a product needs a dynamic routing policy, that is a separate task with its own rules.

Extend the teaching project

We continue one teaching Symfony project, article_demo, independent of the private platform. We create it once in the first article; later steps add capabilities to the same application. All paths below are relative to the article_demo root.

composer require 'symfony/console:8.1.*' 'symfony/filesystem:8.1.*'
composer require --dev symfony/test-pack
mkdir -p src/Notification src/Application src/Infrastructure src/Command tests/Unit

Dependencies come from public packages. Symfony recipes prepare the basic test configuration and application bootstrapping. The saved composer.lock records the specific installed versions; use composer install later to reproduce that dependency set, as explained by Composer. The branch constraint 8.1.* alone does not pin every patch and transitive package.

The contract and the use case

src/Notification/Notifier.php:

<?php

declare(strict_types=1);

namespace App\Notification;

interface Notifier
{
    /**
     * Record a valid UTF-8 message without CR/LF using the configured local adapter.
     *
     * @throws NotificationFailed
     */
    public function send(string $message): void;
}

src/Notification/NotificationFailed.php:

<?php

declare(strict_types=1);

namespace App\Notification;

final class NotificationFailed extends \RuntimeException
{
}

The method returns void: the call either completes or reports failure through NotificationFailed. For this example, input is valid UTF-8 without CR/LF characters. The contract contains no recipient address, queue identifier, or read receipt. Adding them now would promise capabilities the use case does not have.

The name send describes the use case's intention, but the meaning of success is limited to our local adapters. If network delivery is introduced later, its timing boundaries, retries, and acknowledgements will need to be defined again. Identical signatures alone do not establish identical behaviour.

src/Application/AnnounceNote.php:

<?php

declare(strict_types=1);

namespace App\Application;

use App\Notification\Notifier;

final class AnnounceNote
{
    public function __construct(private Notifier $notifier)
    {
    }

    public function __invoke(string $title): void
    {
        $title = trim($title);

        if ($title === '' || preg_match('//u', $title) !== 1
            || str_contains($title, "\n") || str_contains($title, "\r")) {
            throw new \InvalidArgumentException('Use a non-empty, single-line UTF-8 title.');
        }

        $this->notifier->send('Note ready: '.$title);
    }
}

The use case removes the leading and trailing characters handled by PHP's default trim, then checks for a non-empty string, valid UTF-8, and no internal CR/LF. This is a narrow teaching rule, not universal title normalisation or removal of all Unicode whitespace. A valid title becomes one message.

The constructor receives a Notifier; there is no new TextFileNotifier, selection by class name, or container access inside it. Nor does the use case inspect the concrete adapter after the call. Both implementations must meet this use case's needs through the agreed contract.

Two local adapters

src/Infrastructure/TextFileNotifier.php:

<?php

declare(strict_types=1);

namespace App\Infrastructure;

use App\Notification\NotificationFailed;
use App\Notification\Notifier;
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
use Symfony\Component\Filesystem\Filesystem;

final class TextFileNotifier implements Notifier
{
    public function __construct(private Filesystem $filesystem, private string $path)
    {
    }

    public function send(string $message): void
    {
        try {
            $this->filesystem->appendToFile($this->path, $message."\n", true);
        } catch (IOExceptionInterface $exception) {
            throw new NotificationFailed('The local notification could not be recorded.', 0, $exception);
        }
    }
}

src/Infrastructure/JsonLinesNotifier.php:

<?php

declare(strict_types=1);

namespace App\Infrastructure;

use App\Notification\NotificationFailed;
use App\Notification\Notifier;
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
use Symfony\Component\Filesystem\Filesystem;

final class JsonLinesNotifier implements Notifier
{
    public function __construct(private Filesystem $filesystem, private string $path)
    {
    }

    public function send(string $message): void
    {
        try {
            $line = json_encode(['message' => $message], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);
            $this->filesystem->appendToFile($this->path, $line."\n", true);
        } catch (IOExceptionInterface|\JsonException $exception) {
            throw new NotificationFailed('The local notification could not be recorded.', 0, $exception);
        }
    }
}

The first adapter appends the message and a newline. The second appends a JSON object with a message field and also ends the record with a newline. The message structure and the decision about its content remain outside the file handling code.

The official Symfony Filesystem component creates a missing file and parent directories for appendToFile; the third argument, true, enables locking during writing. A lock does not turn the file into a queue with a delivery guarantee. It also gives us no basis to promise transactions, automatic recovery, or freedom from duplicates after a retry.

An IOExceptionInterface becomes the cause of our operation's narrow exception. The JSON adapter also converts JsonException. PHP requires UTF-8 for strings passed to json_encode, and JSON_THROW_ON_ERROR enables error reporting through an exception; these conditions are described in the PHP documentation. The use case validates input earlier, but the adapter must not silently treat failed encoding as a completed write.

We retain the previous exception for diagnostics. The command will show a general message rather than a technical path. A write failure does not prove that no bytes reached the file, so a blind retry may create a duplicate. A task requiring “exactly once” needs a different model and a separate experiment.

Where Symfony chooses the implementation

config/notifier.yaml:

Create config/notifier.yaml with the contents below. Add - { resource: notifier.yaml } once to the top-level imports block in config/services.yaml, creating that block if needed. Preserve the existing services block.

services:
    _defaults:
        autowire: true
        autoconfigure: true

    Symfony\Component\Filesystem\Filesystem: ~
    App\Application\AnnounceNote: ~
    App\Command\AnnounceNoteCommand: ~

    App\Infrastructure\TextFileNotifier:
        arguments:
            $path: '%kernel.project_dir%/var/notifications-%kernel.environment%.txt'

    App\Infrastructure\JsonLinesNotifier:
        arguments:
            $path: '%kernel.project_dir%/var/notifications-%kernel.environment%.jsonl'

    App\Notification\Notifier:
        alias: App\Infrastructure\TextFileNotifier

autowire: true lets the container match dependencies using argument types. However, the Notifier type alone does not explain which of the two adapters is wanted. An explicit alias associates that type with a particular service. This way of selecting an interface implementation is described in the Symfony autowiring documentation.

The path is a scalar argument, so its value is configured separately. The environment name is part of the filename so that local dev and test runs do not use the same name. This is a convenience for the teaching example, not a complete isolation or access management policy.

The container assembles the object graph, and the use case receives the dependency already selected. autoconfigure: true assists registration of the Console command with its AsCommand attribute; the alias chooses the notifier itself. The interface, automatic injection, and configuration choice have different roles, even though they work together.

One entry point through Console

src/Command/AnnounceNoteCommand.php:

<?php

declare(strict_types=1);

namespace App\Command;

use App\Application\AnnounceNote;
use App\Notification\NotificationFailed;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\Console\Output\OutputInterface;

#[AsCommand(name: 'app:note:announce', description: 'Record a local demonstration notification.')]
final class AnnounceNoteCommand extends Command
{
    public function __construct(private AnnounceNote $announceNote)
    {
        parent::__construct();
    }

    protected function configure(): void
    {
        $this->addArgument('title', InputArgument::REQUIRED, 'The note title');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $errorOutput = $output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : $output;

        try {
            ($this->announceNote)((string) $input->getArgument('title'));
        } catch (\InvalidArgumentException $exception) {
            $errorOutput->writeln($exception->getMessage(), OutputInterface::OUTPUT_RAW);

            return Command::INVALID;
        } catch (NotificationFailed $exception) {
            $errorOutput->writeln($exception->getMessage(), OutputInterface::OUTPUT_RAW);

            return Command::FAILURE;
        }

        $output->writeln('Recorded by the configured local adapter.', OutputInterface::OUTPUT_RAW);

        return Command::SUCCESS;
    }
}

The command only passes the title to the use case and presents the result. It returns Command::INVALID for invalid input, Command::FAILURE for an adapter failure, and Command::SUCCESS for a completed call. These are values 2, 1, and 0 respectively in Symfony Console. The success message comes after the use case call, so an exception should not be accompanied by a success acknowledgement.

This example uses the supported configure and execute style. The command's external format does not determine the use case's dependencies: the same object can be called from another entry point by passing a string. A new controller or queue is unnecessary for demonstrating DI.

After creating the files, check the configuration and make the first local call:

APP_ENV=dev php bin/console lint:yaml config/notifier.yaml
APP_ENV=dev php bin/console lint:container
APP_ENV=dev php bin/console debug:autowiring 'App\Notification\Notifier'
APP_ENV=dev php bin/console app:note:announce 'Dependency Injection'
cat var/notifications-dev.txt

With the initial alias, the expected file is var/notifications-dev.txt, and its new line should contain Note ready: Dependency Injection. The command should report Recorded by the configured local adapter.. These are expected signs to check yourself; examine the exit code, the file, and its contents together.

In config/notifier.yaml, change only the target of the existing App\Notification\Notifier alias, without adding a second key with the same name:

    App\Notification\Notifier:
        alias: App\Infrastructure\JsonLinesNotifier

Repeat the call after refreshing the container:

APP_ENV=dev php bin/console cache:clear
APP_ENV=dev php bin/console lint:container
APP_ENV=dev php bin/console app:note:announce 'Dependency Injection'
cat var/notifications-dev.jsonl

The new message should now appear in var/notifications-dev.jsonl as the object {"message":"Note ready: Dependency Injection"}. The old text file remains as the result of the previous run; its presence does not prove that the current adapter still writes to it. Compare the new record and the file sizes before and after the call.

The code of AnnounceNote stays unchanged. To return to the first variant, restore the alias to App\Infrastructure\TextFileNotifier and clear the dev cache again. All commands here specify the environment explicitly, so you do not accidentally check different configurations.

A double that reveals the use case's need

tests/Unit/AnnounceNoteTest.php:

<?php

declare(strict_types=1);

namespace App\Tests\Unit;

use App\Application\AnnounceNote;
use App\Notification\NotificationFailed;
use App\Notification\Notifier;
use PHPUnit\Framework\TestCase;

final class AnnounceNoteTest extends TestCase
{
    public function testRecordsOneMessageFromTheNormalizedTitle(): void
    {
        $notifier = new RecordingNotifier();
        $announce = new AnnounceNote($notifier);

        $announce('  Dependency Injection  ');

        self::assertSame(['Note ready: Dependency Injection'], $notifier->messages);
    }

    public function testRejectsInvalidTitlesWithoutCallingTheAdapter(): void
    {
        $notifier = new RecordingNotifier();
        $announce = new AnnounceNote($notifier);

        foreach (['', '   ', "First\nSecond", "First\rSecond", "Invalid\xFF"] as $title) {
            try {
                $announce($title);
                self::fail('An invalid title must be rejected.');
            } catch (\InvalidArgumentException) {
                self::assertSame([], $notifier->messages);
            }
        }
    }

    public function testPreservesUtf8AndLiteralMarkup(): void
    {
        $notifier = new RecordingNotifier();

        (new AnnounceNote($notifier))('Нотатка <info>DI</info>');

        self::assertSame(['Note ready: Нотатка <info>DI</info>'], $notifier->messages);
    }

    public function testPropagatesTheAdapterFailure(): void
    {
        $failure = new NotificationFailed('Simulated failure.');
        $notifier = new class($failure) implements Notifier {
            public function __construct(private NotificationFailed $failure)
            {
            }

            public function send(string $message): void
            {
                throw $this->failure;
            }
        };

        $this->expectExceptionObject($failure);

        (new AnnounceNote($notifier))('Dependency Injection');
    }
}

final class RecordingNotifier implements Notifier
{
    /** @var list<string> */
    public array $messages = [];

    public function send(string $message): void
    {
        $this->messages[] = $message;
    }
}

Run this particular test, which is provided in full:

APP_ENV=test php bin/phpunit tests/Unit/AnnounceNoteTest.php --testdox

The double collects messages in an array. The first test checks the rule's result and exactly one call through exact list equality. The invalid input check expects an empty list: the adapter must not receive a message after the title is rejected. A separate case preserves UTF-8 and literal text, while a failing double checks propagation of the exception.

The test does not boot the container, open a file, or prove that the YAML is correct. That is precisely why it illustrates the use case's dependency well: an object with one method is enough to check its rule. Nevertheless, both adapters still need checks with real temporary files, a write failure, and a compiled container. A successful double alone does not establish that the infrastructure replacement works.

What to check during your own replacement

Before changing anything, save the initial configuration and make sure you are examining files in your new project. After the change, check both that JSONL appears and that another call has not enlarged the old text file. This distinguishes the actual adapter selection from a case where an earlier run's result is merely still present.

Separately, supply an empty title and a title made of spaces. The expectation is different here: an input error, no write acknowledgement, and no new message in either file. An adapter failure needs a separate, controlled situation: for example, a temporary directory in place of a file path in a dedicated test configuration. Do not change permissions on working directories to manufacture this case.

These checks answer different questions. The double shows the use case's interaction with the contract. A temporary file shows a particular adapter's behaviour. The compiled container shows the configuration choice. The real command combines them and adds the process exit code. No single check replaces all the others, but each has a clear, limited responsibility.

When this contract is worthwhile

A useful boundary appears where the use case's need is more stable than the mechanics of carrying it out. In our case, the rule prepares a message while the method of local recording changes. Judge a new adapter by whether it preserves the agreed meaning of success and failure, not just by the presence of implements Notifier.

If an application always needs only one simple object, with no alternatives and no distinct responsibility boundary, an extra interface may merely add files. The benefit here is specific: two recording options, an explicit selection point, and a rule that can be checked without a file environment. We can explain that benefit without universal promises about development speed.

A configuration replacement does not update every site automatically either. Delivering a verified change to consumers remains a separate issue, as in “How one fix to a shared foundation reaches sites”. Our checkpoint here is closer: does one use case apply the same rule after its dependency is replaced, and has the container actually supplied the intended adapter?

  1. Symfony Core Two profiles, one contract: testing the boundary of reuse
  2. Architecture Configuration or a new implementation: when to stop adding settings
  3. Symfony Core Independent sites with a shared Symfony foundation

A project by the author · Weather Solution200

After reading, a look outside.

Temperature, rain and wind in your city. Check the forecast and plan the hours ahead.

Check the forecast
Next article