Last active
May 14, 2019 17:43
-
-
Save blackandred/1f82e81444e9ac498919561d06e52ee5 to your computer and use it in GitHub Desktop.
Symfony 4: Trait + Setter injection
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 declare(strict_types = 1); | |
namespace App\Core\DependencyInjection\Extension; | |
use App\Core\Service\Serializer; | |
/** | |
* Extends the class with awareness of Serializer service | |
* | |
* Created for free for the anarchist movement around the world. | |
* See iwa-ait.org, zsp.net.pl, wolnosciowiec.net | |
*/ | |
trait SerializerAware | |
{ | |
/** | |
* @var Serializer $serializer | |
*/ | |
protected $serializer; | |
/** | |
* Setter injector (for the container usage) | |
* | |
* @param Serializer $serializer | |
*/ | |
public function setSerializer(Serializer $serializer) | |
{ | |
if ($this->serializer instanceof Serializer) { | |
return; | |
} | |
$this->serializer = $serializer; | |
} | |
protected function getSerializer(): Serializer | |
{ | |
return $this->serializer; | |
} | |
} |
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 declare(strict_types = 1); | |
namespace App\Core\DependencyInjection\Compiler; | |
use App\Core\DependencyInjection\Extension\SerializerAware; | |
use App\Core\Service\Serializer; | |
use Symfony\Component\DependencyInjection\{ContainerBuilder, Reference}; | |
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; | |
/** | |
* Inject Serializer service in every class where a trait "SerializerAware" is used | |
* (uses setter injection) | |
* | |
* Created for free for the anarchist movement around the world. | |
* See iwa-ait.org, zsp.net.pl, wolnosciowiec.net | |
*/ | |
class SerializerInjectionPass implements CompilerPassInterface | |
{ | |
public function process(ContainerBuilder $container) | |
{ | |
foreach ($container->getDefinitions() as $definition) { | |
if (is_subclass_of($definition->getClass(), SerializerAware::class)) { | |
$definition->addMethodCall('setSerializer', new Reference(Serializer::class)); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment