Skip to content

Instantly share code, notes, and snippets.

@MedUnes
Created March 1, 2022 22:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MedUnes/5f57a004c59dacd2fe19cf56ea2c18f9 to your computer and use it in GitHub Desktop.
Save MedUnes/5f57a004c59dacd2fe19cf56ea2c18f9 to your computer and use it in GitHub Desktop.
A kernel patch for Aware based auto DI injection in Symfony
<?php
// src/Kernel.php
namespace App;
use DateTime;
use Psr\Log\LoggerAwareInterface;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
class Kernel extends BaseKernel implements CompilerPassInterface
{
use MicroKernelTrait;
public function process(ContainerBuilder $container): void
{
$definitions = $container->getDefinitions();
foreach ($definitions as $definition) {
if (!$this->isAware($definition, LoggerAwareInterface::class)) {
continue;
}
$definition->addMethodCall(
'setLogger',
[$container->getDefinition('monolog.logger')]
);
}
}
private function isAware(Definition $definition, string $awarenessClass): bool
{
$serviceClass = $definition->getClass();
if ($serviceClass === null) {
return false;
}
$implementedClasses = @class_implements($serviceClass, false);
if (empty($implementedClasses)) {
return false;
}
if (\array_key_exists($awarenessClass, $implementedClasses)) {
return true;
}
return false;
}
}
<?php
// src/Command/MyCommand.php
declare(strict_types=1);
namespace App\Command;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
#[AsCommand(
name: 'app:my-command',
description: 'test!',
)]
class MyCommand extends Command implements LoggerAwareInterface
{
use LoggerAwareTrait;
protected function execute(InputInterface $input, OutputInterface $output): int
{
$this->logger->info('I can log!');
return Command::SUCCESS;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment