VOOZH about

URL: https://deepwiki.com/hypervel/container/3.1-container-implementation

⇱ Container Implementation | hypervel/container | DeepWiki


Loading...
Menu

Container Implementation

This document provides a detailed examination of the Container class implementation, including its internal data structures, inheritance architecture, and core mechanisms. It focuses on how the container stores and manages bindings, instances, and callbacks internally.

For information about the container's public API contract, see Container Contract. For how to use binding methods, see Service Binding. For the resolution process from a user perspective, see Dependency Resolution.

Class Architecture

The Container class extends Hyperf's base container while implementing multiple interfaces to provide enhanced functionality.

Inheritance and Interface Implementation


Diagram: Container Class Hierarchy

The Container class at src/Container.php17 extends Hyperf\Di\Container and implements both Hypervel\Container\Contracts\Container and ArrayAccess. This multi-layered inheritance provides PSR-11 compliance through Hyperf's base implementation while adding Laravel-style container features through the custom contract.

Sources: src/Container.php1-17

Key Architectural Decisions

AspectImplementationRationale
Parent ClassHyperf\Di\ContainerLeverages Hyperf's existing DI infrastructure, definition management, and autowiring capabilities
Custom InterfaceContracts\ContainerDefines Laravel-compatible API surface for familiar developer experience
ArrayAccessImplementedEnables array syntax for binding/resolution: $container['service']
Static InstanceApplicationContextUses Hyperf's context system for global container access

Sources: src/Container.php17

Internal Data Structures

The Container class maintains multiple internal registries to manage different aspects of dependency injection. These arrays work together to provide the full container functionality.


Diagram: Internal Data Structures and Resolution Flow

Sources: src/Container.php19-94 src/Container.php109-132

Property Reference Table

PropertyTypePurposeKey Operations
methodBindingsarray<string, Closure>Stores method-specific resolution logic for call()Set via bindMethod(), checked via hasMethodBinding()
aliasesarray<string, string>Maps alias names to their canonical abstract namesSet via alias(), resolved via getAlias()
abstractAliasesarray<string, array>Reverse mapping: abstract name to all its aliasesMaintained automatically when aliases are registered
extendersarray<string, array<Closure>>Closures that modify instances after instantiationAdded via extend(), applied during make()
reboundCallbacksarray<string, array<Closure>>Callbacks fired when a binding is replacedRegistered via rebinding(), fired during bind()
globalBeforeResolvingCallbacksarray<Closure>Runs before any service resolutionAdded via beforeResolving(Closure)
globalResolvingCallbacksarray<Closure>Runs during any service resolutionAdded via resolving(Closure)
globalAfterResolvingCallbacksarray<Closure>Runs after any service resolutionAdded via afterResolving(Closure)
beforeResolvingCallbacksarray<string, array<Closure>>Type-specific pre-resolution callbacksAdded via beforeResolving(string, Closure)
resolvingCallbacksarray<string, array<Closure>>Type-specific resolution callbacksAdded via resolving(string, Closure)
afterResolvingCallbacksarray<string, array<Closure>>Type-specific post-resolution callbacksAdded via afterResolving(string, Closure)

Sources: src/Container.php19-94

Inherited Properties from Hyperf

The container also inherits critical storage from Hyperf\Di\Container:

PropertyTypePurpose
definitionSourceDefinitionSourceContains all service definitions loaded from configuration files
resolvedEntriesarrayCaches singleton instances to avoid re-instantiation
fetchedDefinitionsarrayCaches fetched definition objects for performance

Sources: src/Container.php17

Core Resolution Pipeline

The make() method implements the complete service resolution pipeline, orchestrating multiple stages of processing.


Diagram: Service Resolution Sequence

Sources: src/Container.php109-132

Resolution Stage Details

Stage 1: Alias Resolution

At src/Container.php111-113 the container first checks if the requested name is an alias and resolves it to the canonical abstract name.


Diagram: Alias Resolution Algorithm

The getAlias() method at src/Container.php623-628 recursively resolves aliases until reaching the canonical name.

Sources: src/Container.php111-113 src/Container.php231-234 src/Container.php623-628

Stage 2: Before Resolving Callbacks

At src/Container.php118 the container fires all registered "before resolving" callbacks. The implementation at src/Container.php522-531 shows a two-phase execution:

  1. Global callbacks: Executed for every resolution
  2. Type-specific callbacks: Executed if the abstract matches or is a subclass

Sources: src/Container.php118 src/Container.php522-531

Stage 3: Parent Container Resolution

At src/Container.php120 the container delegates to Hyperf\Di\Container::make() which handles:

  • Definition retrieval from DefinitionSource
  • Constructor dependency resolution via reflection
  • Actual object instantiation
  • Singleton caching

Sources: src/Container.php120

Stage 4: Extender Application

At src/Container.php125-127 the container applies all registered extenders for the type. Each extender receives the instance and can modify it before returning:


Sources: src/Container.php125-127 src/Container.php633-636

Stage 5: Resolving and After Callbacks

At src/Container.php129 the container fires resolving callbacks, which internally trigger after callbacks at src/Container.php561 The implementation at src/Container.php552-578 shows callback matching logic that includes inheritance checking.

Sources: src/Container.php129 src/Container.php552-578

Binding Management

The container provides multiple binding mechanisms, each with specific behavior for storing and managing service definitions.

Binding Storage Architecture


Diagram: Binding Operation Flow

Sources: src/Container.php243-259 src/Container.php302-307 src/Container.php329-349 src/Container.php314-324

The bind() Method Implementation

The bind() method at src/Container.php243-259 follows this sequence:

  1. Drop stale instances src/Container.php245 - Removes cached instances and aliases for the abstract
  2. Default concrete src/Container.php250-252 - If no concrete provided, uses the abstract as concrete
  3. Check and rebound src/Container.php254-256 - If already bound, fires rebound callbacks
  4. Define src/Container.php258 - Stores the binding in definitionSource

Sources: src/Container.php243-259

The instance() Method Implementation

The instance() method at src/Container.php329-349 handles singleton registration:

  1. Remove abstract alias src/Container.php331 - Cleans up alias mappings
  2. Unset alias src/Container.php333 - Removes direct alias entry
  3. Wrap objects src/Container.php338-340 - Wraps objects in closures for lazy evaluation
  4. Check and rebound src/Container.php342-344 - Fires callbacks if already bound
  5. Define src/Container.php346 - Stores in definition source

Sources: src/Container.php329-349

Alias System

The container implements a bidirectional alias system for flexible service naming.


Diagram: Bidirectional Alias System

Sources: src/Container.php27-38

Alias Registration

The alias() method at src/Container.php374-383 creates bidirectional mappings:

  1. Validation src/Container.php376-378 - Prevents self-aliasing
  2. Forward mapping src/Container.php380 - Stores alias => abstract in aliases array
  3. Reverse mapping src/Container.php382 - Stores abstract => [aliases] in abstractAliases array

Sources: src/Container.php374-383

Alias Resolution Algorithm

The getAlias() method at src/Container.php623-628 implements recursive resolution:


Diagram: Recursive Alias Resolution

This enables alias chains like: 'shortname' => 'alias1' => 'alias2' => 'ConcreteClass'

Sources: src/Container.php623-628

Method Binding System

The container provides a specialized binding system for method-level resolution, used by the call() method.

Method Binding Storage

At src/Container.php20-24 the methodBindings array stores closures keyed by method signatures in Class@method format.


Diagram: Method Binding System

Sources: src/Container.php20-24 src/Container.php264-295

Method Binding Operations

MethodLocationPurpose
bindMethod()src/Container.php272-275Registers a method binding
parseBindMethod()src/Container.php280-287Converts array/string to Class@method format
hasMethodBinding()src/Container.php264-267Checks if a method binding exists
callMethodBinding()src/Container.php292-295Invokes the bound method callback

Sources: src/Container.php264-295

Instance Cache Management

The container inherits singleton caching from Hyperf and adds additional cache management utilities.

Cache Structure


Diagram: Instance Cache Management

Sources: src/Container.php219-226 src/Container.php649-668 src/Container.php673-678

Cache Management Methods

MethodLocationOperationUse Case
resolved()src/Container.php219-226Checks resolvedEntries[abstract]Determine if service has been instantiated
forgetInstance()src/Container.php657-660Removes single entryForce re-resolution on next access
forgetInstances()src/Container.php665-668Clears entire cacheReset container state during testing
dropStaleInstances()src/Container.php649-652Removes instance and aliasAutomatic cleanup during rebinding
flush()src/Container.php673-678Clears cache, aliases, and mappingsComplete container reset

Sources: src/Container.php219-226 src/Container.php649-668 src/Container.php673-678

Singleton and Static Access

The container provides static access patterns through integration with Hyperf's ApplicationContext.


Diagram: Static Container Access Pattern

Sources: src/Container.php683-700

Static Methods

MethodLocationDescription
getInstance()src/Container.php683-692Returns the global container instance, creating one if needed
setInstance()src/Container.php697-700Sets a custom container as the global instance

Both methods delegate to ApplicationContext from hyperf/context for storage, ensuring the container is accessible across the entire application lifecycle.

Sources: src/Container.php683-700

ArrayAccess Implementation

The container implements ArrayAccess to provide convenient array-like syntax for common operations.


Diagram: ArrayAccess and Magic Method Mapping

Sources: src/Container.php702-736

Implementation Mapping

ArrayAccess MethodLocationDelegates ToExample Usage
offsetExists()src/Container.php702-705bound()isset($container['service'])
offsetGet()src/Container.php707-710get()$service = $container['service']
offsetSet()src/Container.php712-715define()$container['service'] = $impl
offsetUnset()src/Container.php717-720remove()unset($container['service'])

Additionally, magic methods at src/Container.php725-736 provide property-like access:

  • __get() delegates to offsetGet()
  • __set() delegates to offsetSet()

Sources: src/Container.php702-736

Integration Points

The container integrates with other system components through well-defined interfaces.


Diagram: Container Integration Architecture

Sources: src/Container.php1-17 src/Container.php437-440

Key Integration Points

  1. Parent Container: Extends Hyperf\Di\Container to inherit core DI functionality including autowiring and definition management
  2. BoundMethod: Delegates method invocation with DI to BoundMethod::call() at src/Container.php437-440
  3. ApplicationContext: Registers as global singleton through Hyperf's context system at src/Container.php686-688
  4. DefinitionSource: Receives definitions from DefinitionSourceFactory during initialization (see Configuration & Initialization)

Sources: src/Container.php1-17 src/Container.php437-440 src/Container.php683-692

Refresh this wiki

On this page