Skip to content

[DI] Support generating interface-bound proxies #20656

Closed
@nicolas-grekas

Description

@nicolas-grekas

May it be useful to make the container able to generate interface-bound proxies?

I see 3 benefits to do so:

  • hiding the concrete class to the consumer, to create a safeguard and enforce talking to its dependency only through the interface-defined contract;
  • these kind of proxies could also be able to instantiate their concrete implementation lazily, in a much simpler way than the generic lazy-proxies generated by https://github.com/Ocramius/ProxyManager;
  • as a side effect, it would allow creating lazy proxies for final classes, thus fix [ProxyManager] Support final classes #20392.

There are two places where this could be enabled, depending on who should have this responsibility:

in the proxyfied-service definition

Assuming Ns\FooClass implements Ns\FooInterface, this could be eg. in XML:

<service id="foo" class="Ns\FooClass" proxy="true" />

so that:

$container->get('foo') instanceof Ns\FooInterface; //==> true
$container->get('foo') instanceof Ns\FooClass; //==> false

lazyness could be activated when the "lazy" attribute is enabled, or be always enabled.
"proxy" attribute being true, all interfaces implemented by the service class would be proxyfied.
We could also imagine a proxy tag that explicitly tells which interfaces should be proxyfied amongst all the implemented one.

in the dependency injecting definition

In XML, this could be eg.:

<service id="foo" class="Ns\FooClass" />
<service id="bar" class="Ns\BarClass">
<argument type="service" proxy="Ns\FooInterface">foo</argument>
</service>

so that inside bar:

$this->foo instanceof Ns\FooInterface; //==> true
$this->foo instanceof Ns\FooClass; //==> false

lazyness could be activated when a "lazy" attribute is enabled, or be always enabled.
In that case, I don't think we should allow proxying several interface at once.

WDYT? (ping @theofidry, maybe you'd like to give it a try?)

Metadata

Metadata

Labels

DependencyInjectionFeatureRFCRFC = Request For Comments (proposals about features that you want to be discussed)

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions