VOOZH about

URL: https://deepwiki.com/friendsofhyperf/components/5-infrastructure-services

⇱ Infrastructure Services | friendsofhyperf/components | DeepWiki


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

Infrastructure Services

Purpose and Scope

This document covers the cross-cutting infrastructure components that provide foundational capabilities for Hyperf applications. These services include caching extensions, distributed locking, encryption utilities, facade patterns, and dynamic configuration management.

For information about helper functions and the dispatch system, see Core Utilities and Helper Functions. For database-related infrastructure like the binlog trigger system, see Database and Model Extensions.


System Architecture

The infrastructure services layer extends Hyperf's core capabilities with additional abstractions, event-driven features, and Laravel-style conveniences. These components are designed to work seamlessly with Hyperf's coroutine-based architecture while providing familiar APIs for developers coming from other frameworks.

Infrastructure Components Overview


Sources: src/cache/composer.json1-48 src/lock/composer.json1-55 src/encryption/composer.json1-56 src/facade/composer.json1-59 src/config-consul/composer.json1-44


Cache Component

The friendsofhyperf/cache component extends Hyperf's cache system with additional features including event dispatching, macroable support, and repository pattern enhancements.

Key Features

FeatureDescriptionImplementation
Event SystemDispatches events on cache operationsCacheFlushed, KeyForgotten events
Macroable SupportAllows runtime method additionsUses Hyperf\Macroable\Macroable trait
Repository PatternEnhanced cache repositoryExtends Hyperf\Cache\Cache
Lock IntegrationOptional lock supportSuggests friendsofhyperf/lock

Events

The cache component dispatches two events for monitoring cache operations:

  • CacheFlushed: Fired when flush() is called on a cache repository
  • KeyForgotten: Fired when forget() or delete() operations succeed

These events enable tracking cache invalidations for debugging and metrics collection.

Dependencies


Sources: src/cache/composer.json1-48 CHANGELOG-3.1.md306


Lock Component

The friendsofhyperf/lock component provides distributed locking capabilities with multiple backend drivers. Locks are essential for preventing race conditions in concurrent environments.

Lock System Architecture


Lock Driver Capabilities

DriverUse CaseDistributedTTL SupportAuto-Release
RedisLockMulti-server environments
DatabaseLockShared database environments
CoroutineLockSingle-process coordination
FileLockSingle-server file locking

Lock Interface Methods

The AbstractLock base class provides the following methods (as of v3.1.75):

acquire(callable $callback = null, $seconds = null) // Acquire the lock
release() // Release the lock
refresh(int $seconds) // Extend lock TTL
isExpired() // Check if expired
getRemainingLifetime() // Get remaining TTL
get(callable $callback) // Acquire and execute
block(int $seconds, callable $callback = null) // Blocking acquire

The class implements Hyperf\Macroable\Macroable, allowing runtime method additions.

Configuration Example


Usage Pattern


Sources: src/lock/composer.json1-55 CHANGELOG-3.1.md17 CHANGELOG-3.1.md52


Encryption Component

The friendsofhyperf/encryption component provides encryption and decryption capabilities with support for key rotation and closure serialization.

Architecture


Key Features

  • AES Encryption: Uses AES-128-CBC or AES-256-CBC ciphers
  • Key Rotation: Supports multiple previous keys for decryption
  • Closure Serialization: Can encrypt serialized closures with opis/closure
  • Event Dispatching: Fires events for key rotation scenarios
  • Coroutine-Safe: Uses Hyperf\Context\Context for thread safety

Configuration


Helper Functions

The component provides global functions defined in src/Functions.php:


Facade Integration

Available through FriendsOfHyperf\Facade\Encryption:


Sources: src/encryption/composer.json1-56 src/macros/composer.json32


Configuration and Service Discovery

The friendsofhyperf/config-consul component enables dynamic configuration management using Consul's Key-Value store, allowing applications to reload configuration without restarts.

Consul Configuration Architecture


Configuration Options


Key-Value Structure

Consul stores configuration as key-value pairs. The driver can parse both flat keys and nested JSON:

Flat Keys:

/config/my-app/database.host = "localhost"
/config/my-app/database.port = "3306"

JSON Values:

/config/my-app/database = {
 "host": "localhost",
 "port": 3306,
 "database": "myapp"
}

Usage

Configuration values are automatically synced and available through Hyperf's config system:


Confd Integration

The related friendsofhyperf/confd component provides integration with Consul for service discovery and configuration management with watch support (as of v3.1.54):


Sources: src/config-consul/composer.json1-44 CHANGELOG-3.1.md346 CHANGELOG-3.1.md959


Facade System

The friendsofhyperf/facade component provides Laravel-style static facades for Hyperf services, offering a clean API while maintaining compatibility with Hyperf's dependency injection container.

Facade Pattern Implementation


Available Facades

The component provides facades for commonly used Hyperf services:

Facade ClassUnderlying ServiceContainer Binding
CacheCache managerHyperf\Cache\CacheInterface
LogLogger instanceHyperf\Logger\LoggerInterface
RedisRedis factoryHyperf\Redis\RedisFactory
Queue / AsyncQueueAsync queue driverHyperf\AsyncQueue\Driver\DriverInterface
DBDatabase connectionHyperf\Database\ConnectionResolverInterface
EventEvent dispatcherPsr\EventDispatcher\EventDispatcherInterface
ValidatorValidator factoryHyperf\Validation\Contract\ValidatorFactoryInterface
ConfigConfigurationHyperf\Contract\ConfigInterface
SessionSession managerHyperf\Session\SessionInterface
ViewView engineHyperf\ViewEngine\Contract\FactoryInterface
EncryptionEncrypterFriendsOfHyperf\Encryption\Encrypter
AmqpAMQP producerHyperf\Amqp\Producer
KafkaKafka producerHyperf\Kafka\Producer

Implementation Pattern

Each facade extends the base Facade class and implements getFacadeAccessor():


The base Facade class handles the static method proxying:

  1. Static calls are intercepted via __callStatic()
  2. The facade accessor is resolved from the DI container
  3. The method call is forwarded to the resolved instance
  4. The instance is stored in Hyperf\Context\Context for coroutine safety

Usage Examples


Dependencies

The facade system depends on:


Suggested dependencies enable specific facades:


Sources: src/facade/composer.json1-59 src/support/composer.json1-62


Integration Patterns

Cache with Lock

Combining the cache and lock components enables atomic cache operations:


Encrypted Configuration

Using encryption with Consul-based configuration:


Facade with Helper Functions

Facades and helper functions work together seamlessly:


Sources: src/cache/composer.json31-33 src/facade/composer.json22-42 src/helpers/composer.json22-41


Coroutine Safety

All infrastructure components are designed to work safely in Hyperf's coroutine environment:

Context Storage Strategy

Components use Hyperf\Context\Context to store per-coroutine state:


Resource Isolation

Each coroutine maintains isolated instances:

  • Cache repositories are resolved per request
  • Lock instances are independent per coroutine
  • Encrypter instances don't share mutable state
  • Facade proxies resolve services per coroutine context

Safe Patterns

The components encourage safe patterns for concurrent execution:


Sources: src/lock/composer.json23-28 src/encryption/composer.json27-32 src/cache/composer.json23-29 CHANGELOG-3.1.md373