-
Notifications
You must be signed in to change notification settings - Fork 34
Decorate
This configuration replaces app.mailer
with a new one, but keeps a reference of the old one as app.decorating_mailer.inner
:
services:
app.mailer:
class: ./AppBundle/Mailer
app.decorating_mailer:
class: ./AppBundle/DecoratingMailer
decorates: app.mailer
arguments: ['@app.decorating_mailer.inner']
public: false
import DecoratingMailer from './DecoratingMailer'
import {Reference} from 'node-dependency-injection'
let definition = container.register('app.decorating_mailer', DecoratingMailer)
definition.decoratedService = 'app.mailer'
definition.addArgument(new Reference('app.decorating_mailer.inner'))
definition.public = false
container.compile()
Here is what's going on here: the decorates option tells the container that the app.decorating_mailer
service replaces the app.mailer
service. By convention, the old app.mailer
service is renamed to app.decorating_mailer.inner
, so you can inject it into your new service.
Most of the time, the decorator should be declared private, as you will not need to retrieve it as app.decorating_mailer
from the container.
The visibility of the decorated app.mailer
service (which is an alias for the new service) will still be the same as the original app.mailer
visibility.
The generated code will be the following:
let mailerService = new DecoratingMailer(new Mailer()));
Remeber compile the container to decorate definitions
If you want to apply more than one decorator to a service, you can control their order by configuring the priority of decoration, this can be any integer number (decorators with higher priorities will be applied first).
services:
foo:
class: Foo
bar:
class: Bar
public: false
decorates: foo
decoration_priority: 5
arguments: ['@bar.inner']
baz:
class: Baz
public: false
decorates: foo
decoration_priority: 1
arguments: ['@baz.inner']
import {Reference} from 'node-dependency-injection';
container.register('foo', Foo)
let definition = container.register('bar', Bar)
definition.addArgument(new Reference('bar.inner'))
definition.public = false
definition.decoratedService = 'foo'
definition.decorationPriority = 5
let definition = container.register('baz', Baz)
definition.addArgument(new Reference('baz.inner'))
definition.public= false
definition.decoratedService = 'foo'
definition.decorationPriority = 1
The generated code will be the following:
let fooService = new Baz(new Bar(new Foo())));
Copyright © 2023-2024 Mauro Gadaleta