Description
Most people go over inheritance instead of composition when overwriting services. But the best way would be always go with composition when decorate the service. A maker make:service-decorator
could automatically detect the interfaces which a decorated service implements and use so the composition when decorating services and call the inner service e.g.:
class SomeService implements SomeInterface
{
public function someMethod(): string
{
return 'test';
}
public function some2Method(): string
{
}
}
interface SomeInterface {
public function someMethod(): string;
public function some2Method(): void;
}
Calling bin/console make:service-decorator
does:
#[AsDecorator(decorates: SomeService::class)]
class DecoratorService implements SomeInterface
{
public function __construct(private #[MapDecorated] SomeInterface $inner)
{}
public function someMethod(): string
{
return $this->inner->someMethod();
}
public function someMethod(): void
{
$this->inner->some2Method();
}
}
An idea i just came to my mind while helping somebody decorate a service correctly, one common issue is also that AsDecorator
requires the service id and people are used to write a class in it, there a maker could help with Did you mean service ...
. In this specific case it was a twig extra extension which only has a service id and not a public class alias in the container.