VOOZH about

URL: https://deepwiki.com/friendsofhyperf/components/5.4-facade-system

⇱ Facade System | friendsofhyperf/components | DeepWiki


Loading...
Last indexed: 14 February 2026 (15d5ca)
Menu

Facade System

Purpose and Scope

The Facade System provides static interfaces to 20+ Hyperf services, enabling convenient access to framework components without requiring explicit dependency injection. This component implements the Facade pattern adapted for Hyperf's coroutine-based architecture, integrating with the DI container and Context system to maintain proper instance resolution and coroutine isolation.

For information about helper functions that complement facades, see Global Helper Functions. For details on the DI container that facades resolve from, see Component Dependencies and Layer Architecture.

Sources: src/facade/composer.json1-59


Architecture Overview

The facade system operates as a bridge between static method calls and dynamic service resolution from Hyperf's dependency injection container. Each facade class provides a static interface that transparently resolves the underlying service instance on each method call, ensuring proper coroutine context isolation.


Facade Resolution Flow

Sources: src/facade/composer.json22-26 src/facade/composer.json44-46


Base Facade Implementation

All facades extend from a base abstract class provided by the friendsofhyperf/support package. This base class implements the static method interception pattern using PHP's __callStatic magic method.

Core Components

ComponentLocationPurpose
Abstract Facade Basefriendsofhyperf/supportProvides static proxy mechanism
ConfigProviderFriendsOfHyperf\Facade\ConfigProviderRegisters facade service bindings
DI Containerhyperf/diResolves service instances
Context Managerhyperf/contextMaintains coroutine-local instances

Resolution Pattern

Each facade class must implement a single method that identifies the service to resolve:

  1. getFacadeAccessor() - Returns the service identifier (container binding key)
  2. Static Method Call - Intercepted by __callStatic() in base class
  3. Instance Resolution - Service resolved from DI container via Context
  4. Method Forwarding - Call forwarded to resolved instance
  5. Result Return - Method result returned to caller

Sources: src/facade/composer.json23-25


Available Facades

The facade component provides static interfaces to the following Hyperf services:


Facade Catalog by Category

Infrastructure Facades

Facade ClassService AccessorRequired PackagePurpose
Cachecache.storehyperf/cacheCache repository operations
Redisredis.connectionhyperf/redisRedis commands
ConfigHyperf\Contract\ConfigInterfacehyperf/configConfiguration access
StorageHyperf\Filesystem\FilesystemFactoryhyperf/filesystemFilesystem operations

Data & Messaging Facades

Facade ClassService AccessorRequired PackagePurpose
QueueHyperf\AsyncQueue\Driver\DriverFactoryhyperf/async-queueAsync queue operations
AMQPHyperf\Amqp\Producerhyperf/amqpAMQP message production
KafkaHyperf\Kafka\Producerhyperf/kafkaKafka message production
SessionHyperf\Session\SessionManagerhyperf/sessionSession management

Application Service Facades

Facade ClassService AccessorRequired PackagePurpose
LogHyperf\Contract\StdoutLoggerInterfacehyperf/loggerLogging operations
ViewHyperf\ViewEngine\Contract\FactoryInterfacehyperf/viewView rendering
ValidatorHyperf\Validation\Contract\ValidatorFactoryInterfacehyperf/validationData validation
LangHyperf\Contract\TranslatorInterfacehyperf/translationTranslation services
CryptFriendsOfHyperf\Encryption\Contracts\Encrypterfriendsofhyperf/encryptionEncryption/decryption

HTTP Facades

Facade ClassService AccessorRequired PackagePurpose
RequestHyperf\HttpServer\Contract\RequestInterfacehyperf/frameworkHTTP request access
ResponseHyperf\HttpServer\Contract\ResponseInterfacehyperf/frameworkHTTP response building

Sources: src/facade/composer.json27-42


Integration Requirements

The facade component uses a suggest-based dependency model, where each facade requires its corresponding package to be installed separately. This allows applications to install only the facades they need.

Package Dependencies


Dependency Graph

Installation Pattern


Sources: src/facade/composer.json22-42


Coroutine Context Management

Facades in Hyperf must account for coroutine-based concurrency. The base facade implementation uses Hyperf's Context system to maintain proper instance isolation across coroutines.


Coroutine Isolation Pattern

Context Storage Strategy

  1. Per-Coroutine Resolution - Each coroutine gets its own resolved instance
  2. Context Key - Instances stored in Context using facade-specific keys
  3. Automatic Cleanup - Context cleared when coroutine completes
  4. Shared Drivers - Underlying drivers (Redis pools, etc.) remain shared

Sources: src/facade/composer.json24


Usage Patterns

Basic Facade Usage

Facades are accessed via static method calls that mirror the underlying service's API:


Comparison with Helper Functions

The facade system complements the helper functions (see Global Helper Functions):

ApproachSyntaxUse Case
FacadeCache::get('key')Multiple chained calls, IDE autocomplete
Helpercache('key')Quick single operations, global scope
DI$this->cache->get('key')Constructor injection, testing

Method Chaining

Some facades support fluent interfaces:


Sources: src/facade/composer.json1-59


Configuration and Registration

ConfigProvider Integration

The facade component registers its services through the standard Hyperf ConfigProvider pattern:


ConfigProvider Structure

The ConfigProvider returns an array defining:

  • dependencies - Service bindings for facade resolution
  • annotations - Scan paths for annotation-based features
  • commands - Console commands (if any)
  • listeners - Event listeners for facade initialization

Service Registration

Each facade's service must be registered in the container. The registration typically happens through:

  1. Framework Auto-Registration - Core Hyperf services registered automatically
  2. Package ConfigProviders - Optional packages register their services
  3. Application Config - Custom bindings in config/autoload/dependencies.php

Sources: src/facade/composer.json52-57


Testing with Facades

Mock Strategy

When testing code that uses facades, you can replace the resolved service with a mock:


Dependency Injection Alternative

For better testability, consider using constructor injection instead of facades:


Sources: src/facade/composer.json25


Relationship with Other Components

Integration Points


Component Relationships

Dependency Hierarchy

LayerComponentsPurpose
ApplicationUser codeConsumes facades via static calls
Facade Layerfriendsofhyperf/facadeProvides static interfaces
Foundationfriendsofhyperf/supportBase facade implementation
Runtimehyperf/di, hyperf/contextService resolution and isolation
Services14+ optional packagesActual service implementations

Sources: src/facade/composer.json22-42 src/helpers/composer.json22-42 src/macros/composer.json22-39


Performance Considerations

Resolution Overhead

Each facade call incurs a small overhead for:

  1. Static Method Interception - __callStatic magic method
  2. Container Resolution - Service lookup from DI container
  3. Context Management - Coroutine-local instance retrieval

For performance-critical code paths:

  • Cache Resolved Instances - Store resolved service in class properties
  • Use Direct Injection - Constructor injection avoids repeated resolution
  • Batch Operations - Group multiple calls to minimize overhead

Instance Caching

The base facade typically caches resolved instances in the coroutine context:


Sources: src/facade/composer.json24-25


Advanced Features

Custom Facade Creation

To create a custom facade for your services:

  1. Define Service Interface

  1. Implement Service

  1. Create Facade Class

  1. Register in Container

Runtime Facade Swapping

Facades can be swapped at runtime for testing or feature toggling:


Sources: src/facade/composer.json44-57


Comparison with Laravel Facades

The friendsofhyperf/facade system is inspired by Laravel's facades but adapted for Hyperf's coroutine architecture:

FeatureLaravel FacadesHyperf Facades
Base PatternStatic proxy to containerSame
ResolutionSingle instance per requestPer-coroutine instances
ContextRequest-scopedCoroutine Context
TestingFacade::spy(), ::fake()Manual container manipulation
Real-time FacadesSupportedNot implemented
Async SafetyNot requiredCoroutine-safe via Context

Key Differences

  1. Coroutine Isolation - Hyperf facades must maintain separate instances per coroutine to avoid data corruption in concurrent request processing
  2. Context Manager - Uses hyperf/context instead of request-scoped storage
  3. No Facade Root - Hyperf doesn't have Laravel's getFacadeRoot() method
  4. Manual Testing - No built-in fake/spy methods; requires container manipulation

Sources: src/facade/composer.json1-59


Summary

The Facade System provides a convenient static interface layer over Hyperf's service container, enabling Laravel-style syntax while maintaining coroutine safety through Hyperf's Context system. With support for 20+ services and 14 optional integration packages, it offers a familiar development experience for developers transitioning from Laravel while respecting Hyperf's asynchronous architecture.

Key Characteristics:

  • Static proxy pattern for service access
  • Coroutine-safe via Context isolation
  • Modular installation of individual facades
  • Compatible with helper functions and macros
  • Testable through container manipulation
  • Minimal performance overhead with instance caching

For related functionality, see Global Helper Functions for function-based alternatives, Cache Component for the underlying cache service, and Lock Component for distributed locking accessed via facades.

Sources: src/facade/composer.json1-59

Refresh this wiki

On this page