Dependency injection for PHP classes that implement third-party interfaces
There are two ways to register an implementation of an interface from a third-party source, such as another PHP package:
- Register the interface implementation globally within the container via a configuration file.
- Inject a specific implementation of an interface into a particular parameter.
The choice of approach depends on the specific task at hand.
Below, we will look at how to configure the container for PSR-3: Logger Interface and the PHP package Monolog.
PHP classes
<?php
declare(strict_types=1);
// file: /app/Services/Foo.php
namespace App\Services;
use Psr\Log\LoggerInterface;
final class Foo
{
public function __construct(
public readonly LoggerInterface $logger
) {}
// …
}<?php
declare(strict_types=1);
// file: /app/Services/Bar.php
namespace App\Services;
use Psr\Log\LoggerInterface;
final class Bar
{
public function __construct(
public readonly LoggerInterface $logger
) {}
// …
}The documentation provides an example of a logger configuration:
<?php
use Monolog\Level;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
// create a log channel
$log = new Logger('name');
$log->pushHandler(new StreamHandler('path/to/your.log', Level::Warning));
// add records to the log
$log->warning('Foo');
$log->error('Bar');As the example shows, for a flexible logger configuration, we can define several arguments within the container parameters:
'name'– the name of the logger channel'path/to/your.log'– the logger file\Monolog\Level::Warning– the logging level for messages
<?php
declare(strict_types=1);
// file: /app/config/parameters.php
use Monolog\Level;
return [
'app_logger.name' => 'my-app_logger',
'app_logger.file' => '/var/logs/app.log',
'app_logger.level' => Level::Warning,
];To declare the implementation of an interface, you can use different options, for example, using an anonymous function and the helper function diCallable(), or a factory[1] method of a PHP class and the helper function diFactory(). You can also define dependency injection for the parameters of an interface implementation's methods by using helper functions or attributes.
Let's select the helper function diAutowire() or attribute \Kaspi\DiContainer\Attributes\Autowire to declare the implementation of the interface \Psr\Log\LoggerInterface.
Global declaration of interface implementation
Globally declaring that a specific PHP class implements an interface allows the container to automatically inject that class as a dependency whenever a method parameter or a callable[2] argument is type-hinted with \Psr\Log\LoggerInterface.
Important note: it is essential to ensure that the same object — the one implementing the interface — is injected each time, rather than creating a new instance for every dependency injection.
Since the \Psr\Log\LoggerInterface is provided by a third party, and we do not have direct access to its source code, we cannot use the \Kaspi\DiContainer\Attributes\Service attribute to declare the implementation.
To address this, we can define the interface implementation in the services.php configuration file using the diAutowire() helper function, where the container identifier[3] is set to the FQCN[4] of the interface, mapped to the \Monolog\Logger PHP class.
<?php
declare(strict_types=1);
// file: /app/src/container_build.php
require_once __DIR__ . '/../vendor/autoload.php';
use Kaspi\DiContainer\DiContainerBuilder;
use App\Services\{Foo, Bar};
$container = (new DiContainerBuilder())
->import(namespace: 'App\\', src: '/app/src')
->load('/app/config/services.php')
->loadParameters('/app/config/parameters.php')
->build();
$foo = $container->get(Foo::class);
var_dump($foo->logger);
$bar = $container->get(Bar::class);
var_dump($bar->logger);<?php
declare(strict_types=1);
// file: /app/config/services.php
use Psr\Log\LoggerInterface;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use function Kaspi\DiContainer\{diAutowire, diParameter};
return static function (): Generator {
yield LoggerInterface::class => diAutowire(
Logger::class,
isSingleton: true
)
// The argument for the constructor of the PHP Logger class
->bindArguments(
diParameter('app_logger.name'),
)
// Inject a dependency into the PHP Logger class via a setter method
->setup(
'pushHandler',
arguments: [
// The StreamHandler PHP class as an argument for a setter method
diAutowire(StreamHandler::class)
// arguments for the constructor of the PHP class StreamHandler
->bindArguments(
diParameter('app_logger.file'),
diParameter('app_logger.level'),
)
],
);
};<?php
declare(strict_types=1);
// file: /app/config/parameters.php
use Monolog\Level;
return [
'app_logger.name' => 'my-app_logger',
'app_logger.file' => '/var/logs/app.log',
'app_logger.level' => Level::Warning,
];Run the following command in the terminal:
php /app/src/container_build.phpA message like the following will appear:
object(Monolog\Logger)#12 (0) {
}
object(Monolog\Logger)#12 (0) {
}NOTE
Note that the object identifier will be the same for all injected objects in this example, #12. This container behavior is due to the \Monolog\Logger PHP class being specified as the value for the $isSingleton parameter in the diAutowire() helper function.
Injecting an interface implementation into a specific parameter
When defining an injection for a method parameter or a callable type[2:1], you can override the globally configured interface implementation by specifying exactly which implementation should be injected into a particular parameter.
Suppose that, specifically for the PHP class \App\Services\Bar, you need to inject a logger with different parameters for instance, one that writes logs using the Monolog\Handler\SocketHandler.
The required logger configuration:
<?php
use Monolog\Level;
use Monolog\Logger;
use Monolog\Handler\SocketHandler;
// create a log channel
$log = new Logger('app_bar_logger');
$handler = new SocketHandler('udp://remote-server:1234', Level::Debug);
$log->pushHandler($handler);
// add records to the log
$log->warning('Foo');
$log->error('Bar');Let’s move the declaration for the PHP class \Monolog\Handler\SocketHandler into a separate configuration file, services_monolog.php.
<?php
declare(strict_types=1);
// file: /app/config/services_monolog.php
use Monolog\Handler\SocketHandler;
use Monolog\Level;
use function Kaspi\DiContainer\diAutowire;
return static function (): Generator {
yield 'baz_logger.handler' => diAutowire(SocketHandler::class)
// Arguments for the constructor of the PHP class SocketHandler
->bindArguments(
'udp://remote-server:1234',
Level::Debug,
);
};We will use the injection declaration in the $logger constructor parameter of the PHP class \App\Services\Bar via the attribute \Kaspi\DiContainer\Attributes\Autowire, since we can change the code of the PHP class itself.
<?php
declare(strict_types=1);
// file: /app/Services/Bar.php
namespace App\Services;
use Psr\Log\LoggerInterface;
use Kaspi\DiContainer\Attributes\Autowire;
use Monolog\Logger;
use Kaspi\DiContainer\DiDefinition\DiDefinitionParameter as Parameter;
use Kaspi\DiContainer\Attributes\Setup;
use Kaspi\DiContainer\DiDefinition\DiDefinitionGet as DiGet;
final class Bar
{
public function __construct(
#[Autowire(
Logger::class,
arguments: [new Parameter('baz_logger.name')],
setups: [
'pushHandler' => new Setup(
// The reference to a PHP class object
new DiGet('baz_logger.handler')
),
],
)]
public readonly LoggerInterface $logger
) {}
// …
}When building the container, let's add a new configuration file, services_monolog.php:
<?php
declare(strict_types=1);
// file: /app/src/container_build.php
require_once __DIR__ . '/../vendor/autoload.php';
use Kaspi\DiContainer\DiContainerBuilder;
use App\Services\{Foo, Bar};
$container = (new DiContainerBuilder())
->import(namespace: 'App\\', src: '/app/src')
->load('/app/config/services.php')
->loadParameters('/app/config/parameters.php')
->load('/app/config/services_monolog.php')
->build();
$foo = $container->get(Foo::class);
var_dump($foo->logger->getHandlers());
$bar = $container->get(Bar::class);
var_dump($bar->logger->getHandlers());<?php
declare(strict_types=1);
// file: /app/config/services.php
use Psr\Log\LoggerInterface;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use function Kaspi\DiContainer\{diAutowire, diParameter};
return static function (): Generator {
yield LoggerInterface::class => diAutowire(
Logger::class,
isSingleton: true
)
// аргумент в конструктор PHP-класса Logger
->bindArguments(
diParameter('app_logger.name'),
)
// внедрить зависимость в PHP-класс Logger через сеттер-метод
->setup(
'pushHandler',
arguments: [
// PHP-класс StreamHandler как аргумент в сеттер-метод
diAutowire(StreamHandler::class)
// аргументы в конструктор PHP-класса StreamHandler
->bindArguments(
diParameter('app_logger.file'),
diParameter('app_logger.level'),
)
],
);
};<?php
declare(strict_types=1);
// file: /app/config/parameters.php
use Monolog\Level;
return [
'app_logger.name' => 'my-app_logger',
'app_logger.file' => '/var/logs/app.log',
'app_logger.level' => Level::Warning,
];<?php
declare(strict_types=1);
// file: /app/config/services_monolog.php
use Monolog\Handler\SocketHandler;
use Monolog\Level;
use function Kaspi\DiContainer\diAutowire;
return static function (): Generator {
yield 'baz_logger.handler' => diAutowire(SocketHandler::class)
// аргументы в конструктор PHP-класса SocketHandler
->bindArguments(
'udp://remote-server:1234',
Level::Debug,
);
};Run the following command in the terminal:
php /app/src/container_build.phpA message like the following will appear:
array(1) {
[0]=>
object(Monolog\Handler\StreamHandler)#12 (0) {
}
}
array(1) {
[0]=>
object(Monolog\Handler\SocketHandler)#23 (0) {
}
}In some scenarios, it becomes necessary—for the purpose of dependency injection—to employ the "factory" design pattern, delegating the creation of a required object to a dedicated PHP class known as a "factory." ↩︎
The
callabletype represents values or expressions that can be invoked as a function. See the description in the PHP documentation. ↩︎ ↩︎A container ID is a string name (or a class/interface name) used to register a service or object within a container and to retrieve it via the
get()method. ↩︎Fully Qualified Class Name – the full name of a class or interface, including its namespace. ↩︎