Description
Hi,
I was thinking about creating a Form Builder UI. The user could specify the fields and then a FormBuilder
class would be created at runtime. Great !
Just then i noticed the FormBuilder can be feeded some classes that can be services too, like the EventDispatcher
. So in case you need that one you need the EventDispatcher
which was already instantiated by the DIC and not a new one.
After looking around a litlte bit the following resource showed up:
https://www.drupal.org/node/2004282
where @stof points to
#7230
I would like to know if it's feasible to add support for this to the DI component or if it's left to the developer to request services for the unserialized component and figure out how to inject them.
There are some problems with doing it this way. Please consider the general question of injected services into unserialized objects, not just in the context of the FormBuilder, but also as in the linked PR of assetic and other use cases.
- All the required services already need to be instantiated while they might not be needed depending on the type of request (a lazy proxy service already helps here).
- Depending on business logic different services might need to be injected that can change in runtime.
Code could look like this:
# app/config/config.yml
services:
my_service:
class: Some\Sort\OfClass
arguments: [@dependency1]
calls:
- [setDependency2, ["@dependency2"]]
<?php
// Some sort of class
class OfClass {
protected $dependency1;
protected $dependency2;
protected $dependency3; // optional
public function __construct($dependency1) {
}
public function setDependency2($dependency2) {
}
}
// Somewhere else in another file
$fb = $container->wakeup(
"some serialized FormBuilder string",
[
'dependency1' => $runtime_service1, // overwrite
// dependency 2 --> default dependency
'dependency3' => $runtime_service3 // supplemented
]
);
DIC would then do the following:
- unserialize the object
- instantiate dependency graph when not available (optional step i guess)
- choose different dependencies if specified in the
wakeup()
method - inject dependencies. Possible implementation: reflection (a la Doctrine)
- give back object at runtime.
In addition to my question if this would be a good suggestion to the DIC component in specific, i would like to ask if this would be a good attribute to the symfony code wether or not it will be placed in the DIC component.
In conclusion: it's not that hard to make the ugly way when all the services are available from the DIC, but it might be worthwhile to have this functionality available to everyone.
Thoughts?