VOOZH about

URL: https://deepwiki.com/hypervel/components/2.2-service-providers-and-bootstrapping

⇱ Service Providers and Bootstrapping | hypervel/components | DeepWiki


Loading...
Last indexed: 7 March 2026 (96fbab)
Menu

Service Providers and Bootstrapping

This document covers the service provider system and bootstrapping process in Hypervel's foundation layer. Service providers are the primary mechanism for registering and configuring framework services through a two-phase lifecycle: registration followed by booting.

For information about the Application container itself, see Application Container and Lifecycle. For configuration management details, see Configuration Management.

Service Provider Architecture

The ServiceProvider Base Class

Service providers extend Hypervel\Support\ServiceProvider and define two primary methods:

  • register(): Binds services into the container during the registration phase
  • boot(): Performs setup that depends on all services being registered

Providers can optionally declare a $bindings property that the Application automatically processes during registration:

'bindings' => [
 SomeInterface::class => SomeImplementation::class,
]

Sources: src/foundation/src/Application.php311-345

Two-Phase Lifecycle

The service provider system follows a strict two-phase lifecycle to ensure proper dependency resolution:


Phase 1 - Registration:

  • All service providers register their bindings
  • Services are bound to the container but not resolved
  • No cross-service dependencies should be resolved
  • Executed via Application::register()

Phase 2 - Booting:

  • All providers' boot() methods are called
  • Services can be safely resolved from the container
  • Cross-service configuration occurs
  • Executed via Application::boot()

Sources: src/foundation/src/Application.php311-345 src/foundation/src/Application.php398-416

Application Service Provider Management

Registration Phase

The Application::register() method handles service provider registration:


The Application tracks registered providers in two arrays:

  • $serviceProviders: Maps class names to provider instances
  • $loadedProviders: Tracks which providers have been loaded (class name => true)

Key Features:

  • Duplicate Prevention: Returns existing provider unless $force = true
  • String Resolution: Accepts class names and instantiates them automatically
  • Lazy Booting: Immediately boots the provider if the application has already booted
  • Property Bindings: Automatically processes the $bindings property

Sources: src/foundation/src/Application.php311-345 src/foundation/src/Application.php378-385

Booting Phase

The Application::boot() method executes the booting phase:

StepActionMethod
1Check if already bootedisBooted() returns $booted flag
2Fire "booting" callbacksfireAppCallbacks($bootingCallbacks)
3Boot all service providersarray_walk($serviceProviders, bootProvider)
4Set booted flag$booted = true
5Fire "booted" callbacksfireAppCallbacks($bootedCallbacks)

Each individual provider is booted via bootProvider():

  1. Call $provider->callBootingCallbacks()
  2. Call $provider->boot() (if method exists) using container's call() for dependency injection
  3. Call $provider->callBootedCallbacks()

Sources: src/foundation/src/Application.php398-416 src/foundation/src/Application.php421-430

Boot Callbacks

The Application supports callbacks at multiple lifecycle points:


Callback Registration Methods:

  • booting(callable $callback): Registers callback to run before providers boot
  • booted(callable $callback): Registers callback to run after providers boot
    • If application already booted, executes immediately

Sources: src/foundation/src/Application.php435-450 src/foundation/src/Application.php457-466

Bootstrapping Process

The bootstrapWith Method

The bootstrapWith() method executes a series of bootstrap classes in order:


Key Features:

  • Sets hasBeenBootstrapped flag to true
  • Fires before/after events for each bootstrapper
  • Resolves bootstrapper from container (supports dependency injection)
  • Calls bootstrap($app) method on each bootstrapper instance

Hook Methods:

  • beforeBootstrapping(string $bootstrapper, Closure $callback): Listen to "bootstrapping: {class}" event
  • afterBootstrapping(string $bootstrapper, Closure $callback): Listen to "bootstrapped: {class}" event

Sources: src/foundation/src/Application.php118-129 src/foundation/src/Application.php134-145 src/foundation/src/Application.php150-153

Bootstrap vs Service Provider Boot

AspectBootstrap ClassesService Provider Boot
TimingRun once at application initializationCan be registered/booted at any time
PurposeConfigure environment (env, config, error handling)Register and configure services
Methodbootstrap($app)boot()
Events"bootstrapping/bootstrapped: {class}"Provider-specific callbacks
StateSets hasBeenBootstrappedSets booted

Sources: src/foundation/src/Application.php118-153

FoundationServiceProvider

The FoundationServiceProvider is a critical service provider that bridges Hypervel and Hyperf configurations.

Responsibilities Overview


Sources: src/foundation/src/Providers/FoundationServiceProvider.php49-75

Configuration Override System

The overrideHyperfConfigs() method is crucial for framework interoperability:


Configuration Mappings:

Hypervel ConfigHyperf Config KeyPurpose
app.nameapp_nameApplication name
app.envapp_envEnvironment (local, production)
app.stdout_log_levelStdoutLoggerInterface.log_levelConsole log level
database.connectionsdatabasesDatabase connections
database.migrationsdatabases.migrationsMigration table name
database.defaultdatabases.defaultDefault connection config
database.redisredisRedis connections with options

Middleware Configuration:

The provider processes middleware configuration specially:

  1. Reads config/middlewares array
  2. Sorts each server's middleware using MiddlewareManager::sortMiddlewares()
  3. Merges global middleware from kernel classes (via server.kernels config)
  4. Writes final sorted array to config/middlewares

Sources: src/foundation/src/Providers/FoundationServiceProvider.php108-162

Service Registration Details

Enhanced Dumper System

The registerDumper() method configures Symfony VarDumper with Hypervel enhancements:

Cloner Configuration:

  • Adds casters to hide internals: ConnectionInterface, Container, Dispatcher, Grammar
  • Uses StubCaster::cutInternals to reduce noise in dumps

Dumper Selection:

  • Checks $_SERVER['VAR_DUMPER_FORMAT'] environment variable
  • Falls back to auto-detection based on php_sapi_name()
  • Registers either CliDumper or HtmlDumper with source resolution

Source Resolution Features:

  • Resolves original file from compiled view files
  • Extracts path from /**PATH ... ENDPATH*/ comments in compiled views
  • Generates editor links (VSCode, PHPStorm, etc.) for quick navigation

Sources: src/foundation/src/Providers/FoundationServiceProvider.php181-201 src/foundation/src/Concerns/ResolvesDumpSource.php56-113

Request User Resolver

The provider sets up user authentication integration via callAfterResolving():


This allows $request->user() to work seamlessly with the authentication system.

Sources: src/foundation/src/Providers/FoundationServiceProvider.php67-74

URI URL Generation

Registers the UrlGenerator resolver with the Uri class:


This enables the Uri class to generate URLs using the application's URL generator.

Sources: src/foundation/src/Providers/FoundationServiceProvider.php164-169

Boot Phase Operations

Timezone Configuration

Sets PHP's default timezone from config/app.php:


Sources: src/foundation/src/Providers/FoundationServiceProvider.php171-174

Internal Encoding

Sets multibyte string encoding to UTF-8:


Sources: src/foundation/src/Providers/FoundationServiceProvider.php176-179

Database Connection

Sets the default database connection from configuration:


Sources: src/foundation/src/Providers/FoundationServiceProvider.php101-106

Command Exception Handling

The provider listens for FailToHandle events to provide better error output for console commands:


The provider walks the exception's stack trace looking for ConsoleKernel::call() to determine if special rendering should apply.

Sources: src/foundation/src/Providers/FoundationServiceProvider.php77-99

Service Provider Query Methods

The Application provides methods to inspect registered providers:

MethodReturn TypeDescription
getProvider(ServiceProvider|string)?ServiceProviderGet single registered provider instance
getProviders(ServiceProvider|string)ServiceProvider[]Get all instances of a provider type
getLoadedProviders()array<string, bool>Get all loaded provider class names
providerIsLoaded(string)boolCheck if specific provider is loaded
resolveProvider(string)ServiceProviderCreate new provider instance

Sources: src/foundation/src/Application.php350-385 src/foundation/src/Application.php488-499

Complete Lifecycle Flow


Sources: src/foundation/src/Application.php82-90 src/foundation/src/Application.php311-345 src/foundation/src/Application.php398-416 src/foundation/src/Application.php118-129