As mentioned in the SymfonyCon feedback post, every time I add a dependency injection for a service that will be used only once within my service, controller or other, it makes me feel uncomfortable.
Why can't we just say that we need this service, but only load it on demand?
Then I attend the conference Unleashing the power of lazy objects in PHP of Nicolas Grekas who presents his work done on the lazy loading of services. What is going through my mind at this moment :
- How to integrate it in Drupal ?
- When it will be integrated in Drupal ?
- Damn, what he presents is not yet fully published... I'm not ready to see it in Drupal :(
It stays in my head, it goes round and round...
And if ?
I can't stand it anymore, the concept is not so complicated after all... I open the hood of my Drupal...
Good point, we are not late, Drupal already has the possibility to declare a service as lazy. You just have to add to the service declaration the option "lazy: true" and generate its ProxyClass. We are not 100% aligned with the simplified way of Symfony and its annotations, but it is not so bad.
You still have to run a script manually to generate the ProxyClass class in the module directory where the service in question is located.
But not ahead
So we are at the same state as Symfony is now. We can declare a service as "lazy", but we can't, from a service, say that we want to inject, in lazy, a service that was not planned to be.
So are we screwed ? Meet in 2030 ?
If we had to go through an update of the Drupal core to integrate this feature, certainly!
I'm a bad guy, such a feature could certainly come sooner, but in which version of Drupal? 10 ? 11 ?...
Except that we are lucky, Drupal gives us the necessary tools to do this in the form of contrib modules. So we will be able to propose the functionality as a community module, and in parallel push the functionality in the core.
Yes but when ?
There is still work to do, but the code is already available. It remains to improve it, write tests, documentation, open the ticket for integration into the core of Drupal etc.
In the meantime, the module as a proof of concept exists, works on the few tests performed and will be able to go to a direction.
What to do as a developer :
- We declare a service as being a service to be loaded in lazy by prefixing its name during the dependency injection with "lazy". Example for the service "messenger" : "lazy.messenger".
What the module does then:
- The module alters the list of services to generate the corresponding proxyClass on the fly if it does not exist, and finishes declaring the service correctly.
I invite you to take a look and participate, the Lazy service module for Drupal is here.