ServiceManager Shared Instances vs Non-Shared Factories for State Isolation
0 reputation · 26 Aug 2021, 00:39 UTC
In Zend (Laminas) applications, the ServiceManager defaults to caching service instances to minimize instantiation overhead during the request lifecycle. While this reduces latency and memory allocation, it introduces risks when services maintain internal state that must remain isolated between different components within a single execution thread.
Configuring services as non-shared forces the manager to invoke the factory for every retrieval, ensuring a fresh instance. However, this creates a trade-off between strict state isolation and the CPU cycles required for repeated object construction, particularly for heavy dependencies.
Technical Constraints
- Requirement for state purity across disparate components.
- Need to maintain low request bootstrap latency.
- Dependency on the
sharedconfiguration key in the ServiceManager array.
Under what specific conditions does the overhead of non-shared instantiation outweigh the risks of state leakage in a high-concurrency environment? Which approach is more sustainable for services that require dynamic configuration based on the current request context?