-
-
Save MedUnes/5f57a004c59dacd2fe19cf56ea2c18f9 to your computer and use it in GitHub Desktop.
A kernel patch for Aware based auto DI injection in Symfony
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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