Skip to content

Lazy proxy generation via PHP 8.4 native lazy objects #293

Description

@philipobenito

Summary

Add lazy proxy support using PHP 8.4's native ReflectionClass::newLazyGhost() and ReflectionClass::newLazyProxy() APIs, allowing services to defer instantiation until first method call.

Context

Lazy proxies are useful when a service is injected as a constructor argument but may never actually be called, avoiding expensive construction costs. The committee evaluated this for 6.0 but deferred because:

  • Without native lazy object support, implementing proxies requires either a code-generation library (adding a dependency) or substantial bespoke proxy class generation
  • PHP 8.4 introduces ReflectionClass::newLazyGhost() and newLazyProxy() which make this trivial (approximately five lines of code)
  • The current callable-as-concrete pattern already defers instantiation until get() is called, covering the majority of use cases

Implementation notes

  • Requires PHP 8.4 as minimum (or feature-gated with version check)
  • Could be a Definition::setLazy(bool) flag or a #[Lazy] attribute
  • The compiled container would need to emit lazy ghost wrappers in factory methods
  • Semantic question: when does ServiceResolvedEvent fire? When the proxy is created or when the real service is instantiated?

Target

6.2+ (when PHP 8.4 can be the minimum version)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions