On Fri, Mar 7, 2025, at 09:48, Edmond Dantes wrote:
> 
> >
> >  As far as I know, all current SAPIs follow one of two patterns:
> >
> 
> It seems that my example, although taken from real life, is more of an 
> anti-pattern. Let's take a real example that is not an anti-pattern.
> 
> There is a B2B CRM built on services. Services are classes instantiated in 
> memory only once via DI, and all that. We process requests. Requests are 
> executed within a logical *Scope*. The scope depends on the *TOKEN* and 
> reflects the following entities:
> 
>  • *User Profile*
>  • *Company Settings*
> We have two implementation options:
> 
>  1. Pass the user profile and company settings to every method.
>  2. Use some static variable to make the semantics shorter.
> When the application runs in separate processes, there are no issues. What do 
> we do?
> 
>  1. Pass the `UserProfile` object into DI.
>  2. Pass the `CompanySettings` object into DI.
> Everyone is happy. If it’s a *long-running* process, everyone is twice as 
> happy because the already loaded services and resolved DI are reused multiple 
> times for handling requests. Memory copying is reduced, and for fast 
> requests, we get a nice performance boost. This is especially pleasant for 
> users with a good internet connection.
> 
> However, this model will not work if each request is processed in a separate 
> coroutine. There are two possible solutions:
> 
>  1. Pass the *"environment objects"* explicitly through function calls (*I’d 
> like to see developers doing this and staying in a good mood*).
>  2. Use something else.

This sounds like you are not using DI meant for fibers/multiple requests at the 
same time. DI used in large projects like the one that comes with Symfony is 
NOT compatible with this model. These are the basic requirements for DI that 
needs to handle multiple requests on long-running scripts:

- you need "volatile" injections,
- you need "singleton" injections,
- and you need "per request" injections.

"Volatile" injections are injections that provide a new one every time you ask 
for it and "per request" injections are singleton, but only for the current 
request (every request gets a new one and only one for the lifetime of the 
request). The only "services" running between requests and not new'd up every 
request are "singleton" injections. These are stateless services providing 
generic interfaces (such as sending emails, notifications, etc).

This is how .NET does it as well (just with different names), and as far as I 
know, absolutely no DI library in PHP does it this way, and only private, 
custom built DI does it this way; the ones that are using fibers already.

— Rob

Reply via email to