Skip to content

Instantly share code, notes, and snippets.

@blackandred
Last active May 14, 2019 17:43
Show Gist options
  • Save blackandred/1f82e81444e9ac498919561d06e52ee5 to your computer and use it in GitHub Desktop.
Save blackandred/1f82e81444e9ac498919561d06e52ee5 to your computer and use it in GitHub Desktop.
Symfony 4: Trait + Setter injection
<?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;
}
}
<?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