VOOZH about

URL: https://deepwiki.com/friendsofhyperf/components/5.2-lock-component

⇱ Lock Component | friendsofhyperf/components | DeepWiki


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

Lock Component

The Lock component (friendsofhyperf/lock) provides distributed locking functionality for coordinating concurrent operations in Hyperf applications. It supports multiple storage backends (Redis, Database, File) and includes extensible lock lifecycle management through the Macroable trait.

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

Component Overview

The Lock component implements a driver-based distributed locking system that prevents race conditions through exclusive lock acquisition. The component features:

  • Multi-driver support: Redis, Database, and File storage backends
  • AbstractLock base class: Common implementation with Macroable trait for runtime extensions
  • Lifecycle methods: refresh(), isExpired(), getRemainingLifetime() for lock monitoring
  • Coroutine-safe: Integrates with Hyperf's context management for concurrent operations

For cache-specific atomic operations using locks, see page 5.1.

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

Lock Architecture and Driver System

Component Architecture

The Lock component implements a driver-based architecture with three storage backends. All drivers extend AbstractLock which provides the Macroable trait for runtime method extensions.

Lock Architecture Diagram


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

Storage Driver Implementations

The component provides three driver implementations that extend AbstractLock:

Driver ClassStorage BackendRequired PackageScope
FileLockFilesystem via cache adapterhyperf/cacheSingle-server
DatabaseLockDatabase tablehyperf/db-connectionMulti-server
RedisLockRedis key-value storehyperf/redisDistributed

Each driver inherits lifecycle methods from AbstractLock and implements storage-specific acquisition logic.

Sources: src/lock/composer.json30-33

Lock Drivers and Storage Backends

Driver Selection

The Lock component determines which driver to use based on configuration and installed dependencies:

DriverRequired PackageUse CaseLock Scope
filehyperf/cacheSingle-server deploymentsProcess-local
databasehyperf/db-connectionMulti-server with shared databaseCluster-wide
redishyperf/redisHigh-performance distributed lockingCluster-wide

The suggest section in composer.json defines these optional dependencies:


Sources: src/lock/composer.json30-33

Driver Implementation Architecture


Sources: src/lock/composer.json30-33

Lock Lifecycle and Operations

Acquisition Strategies

The Lock component supports two acquisition strategies:

  1. Non-blocking (get): Attempts immediate acquisition, returns false if lock unavailable
  2. Blocking (block): Waits for lock availability up to a specified timeout

Sources: src/lock/composer.json1-55

AbstractLock and Macroable Extension

AbstractLock Base Class

The AbstractLock class provides common lock functionality and includes the Macroable trait, enabling runtime method additions without modifying driver classes.

AbstractLock Structure


Sources: CHANGELOG-3.1.md17 CHANGELOG-3.1.md52

Macroable Trait Integration

The Macroable trait allows dynamic method registration on lock instances:


This extensibility enables application-specific lock behaviors without modifying the core component.

Sources: src/lock/composer.json25 CHANGELOG-3.1.md17

Lock Lifecycle Methods

New Lifecycle Management Methods

Added in v3.1.75, the Lock component now includes methods for monitoring and managing lock state:

MethodReturn TypePurpose
refresh()boolExtends lock TTL without releasing
isExpired()boolChecks if lock has expired
getRemainingLifetime()intReturns seconds until expiration

Lock State Monitoring Diagram


Sources: CHANGELOG-3.1.md52

Lock Ownership and Expiration

Each lock maintains ownership metadata:

  • Owner Token: Unique identifier (UUID) per acquisition
  • Expiration TTL: Prevents deadlocks if process crashes
  • Force Release: Administrative override to break locks

Lock State Lifecycle


Sources: src/lock/composer.json22-28 CHANGELOG-3.1.md52

Lock Integration with Cache Component

The Cache component leverages the Lock component for atomic operations through its repository pattern:


The Cache component's composer.json indicates this dependency:


This integration prevents cache stampede scenarios where multiple concurrent requests attempt to regenerate the same expensive cache value simultaneously.

Sources: src/cache/composer.json31-33

Configuration and Setup

Installation

Install the Lock component individually or as part of the meta-package:


Install the storage backend package for your chosen driver:


Sources: src/lock/composer.json1-55

Configuration Structure

The component registers via ConfigProvider:

Configuration Loading Flow


The ConfigProvider is declared in composer.json:


Sources: src/lock/composer.json47-53

Driver Configuration

The config/autoload/lock.php file specifies the default driver and connection settings:


Publish the configuration template:


Sources: src/lock/composer.json47-53

Lock API and Usage Patterns

Global lock() Helper Function

The component exposes a lock() function for convenient access to the locking system.

Lock Helper Resolution Flow


The helper is autoloaded via composer.json:


Sources: src/lock/composer.json39-41

Lock API Methods

The AbstractLock class provides the following methods:

MethodSignatureDescription
get()get(?callable $callback): mixedNon-blocking acquisition
block()block(int $seconds, ?callable $callback): mixedBlocking acquisition with timeout
acquire()acquire(): boolAcquire lock (returns false if unavailable)
release()release(): boolRelease lock by owner
forceRelease()forceRelease(): voidBreak lock regardless of owner
owner()owner(): stringGet current owner token
refresh()refresh(): boolExtend lock TTL
isExpired()isExpired(): boolCheck if lock expired
getRemainingLifetime()getRemainingLifetime(): intSeconds until expiration

Sources: src/lock/composer.json25 CHANGELOG-3.1.md52

Common Usage Patterns

Try-Lock Pattern (Non-blocking)


Wait-Lock Pattern (Blocking)


Manual Lock Management


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

Testing Lock Operations

Unit Testing with Lock Fakes

The Lock component supports testing by allowing mock implementations:


Sources: tests/Pest.php36

Lock Testing Patterns

Common testing scenarios include:

Test ScenarioVerification
Successful acquisitionacquire() returns true
Lock contentionSecond acquire() fails while first holds lock
TTL expirationisExpired() returns true after timeout
Lock refreshrefresh() extends lifetime
Force releaseforceRelease() breaks lock regardless of owner

Example Test Structure


Sources: tests/Pest.php36 CHANGELOG-3.1.md52

Coroutine Safety and Context Management

The Lock component is designed for Hyperf's coroutine-based architecture and uses hyperf/context for safe state management across coroutines:


This architecture ensures that concurrent coroutines can safely acquire and release different locks without interference, while the shared storage backend enforces mutual exclusion across all processes and servers.

Sources: src/lock/composer.json24