VOOZH about

URL: https://deepwiki.com/hypervel/support/6-data-persistence-layer

⇱ Data Persistence Layer | hypervel/support | DeepWiki


Loading...
Menu

Data Persistence Layer

Purpose and Scope

The Data Persistence Layer provides a unified interface for interacting with various data storage and retrieval mechanisms in the Hypervel framework. This layer abstracts database operations, caching, Redis operations, and asynchronous job queuing through a consistent facade-based API built on top of Hyperf's data management services.

This document covers the architectural patterns and integration points common across all persistence subsystems. For detailed usage of specific components:

For HTTP-related functionality, see HTTP Layer. For view rendering and templates, see View Layer.

Architectural Layers

The Data Persistence Layer follows a four-tier architecture that separates API surface from implementation details:

Layer Structure Diagram


Sources: src/Facades/DB.php1-40 src/Facades/Cache.php1-73 src/Facades/Redis.php1-282 src/Facades/Queue.php1-114

Facade System Integration

All data persistence facades inherit from the base Facade class and implement the getFacadeAccessor() method to resolve their underlying service from the PSR-11 container.

Facade Resolution Mapping

Facade ClassFacade AccessorResolved ServiceFile Location
DBHyperf\DbConnection\Db::classHyperf DB Connection Managersrc/Facades/DB.php35-38
CacheHypervel\Cache\Contracts\Factory::classCache Factory/Managersrc/Facades/Cache.php68-71
RedisHypervel\Redis\Redis::classRedis Client Managersrc/Facades/Redis.php277-280
QueueHypervel\Queue\Contracts\Factory::classQueue Factory/Managersrc/Facades/Queue.php109-112

Method Call Flow


Sources: src/Facades/DB.php33-39 src/Facades/Cache.php66-72 src/Facades/Redis.php275-281 src/Facades/Queue.php78-113

Database Layer

The DB facade provides access to Hyperf's database abstraction layer, supporting multiple database drivers through a unified query builder interface.

DB Facade Methods

The DB facade exposes the following key method categories:

CategoryMethodsDescription
Query Buildingtable(), raw()Construct fluent query builders
Raw Queriesselect(), selectOne(), insert(), update(), delete()Execute raw SQL statements
Transactionstransaction(), beginTransaction(), commit(), rollBack()Manage database transactions
Connection Managementconnection(), transactionLevel()Handle multiple connections
Execution Controlstatement(), affectingStatement(), unprepared()Low-level query execution

Sources: src/Facades/DB.php9-30

Database Connection Resolution


The connection(?string $pool = null) method returns a Hyperf\Database\ConnectionInterface instance, which wraps the underlying PDO connection with query building and transaction capabilities.

Sources: src/Facades/DB.php29

Cache Layer

The Cache facade implements a multi-driver caching system with support for tagging, distributed locking, and typed accessors.

Cache Manager Architecture


Sources: src/Facades/Cache.php9-62

Cache Operations

The Cache facade provides operations across multiple categories:

Operation TypeMethodsReturn Type
Basic Accessget(), set(), has(), forget()mixed, bool
Multi-keymany(), putMany(), getMultiple()array, bool
Conditionaladd(), remember(), rememberForever()bool, mixed
Increment/Decrementincrement(), decrement()`int
Typed Accessstring(), integer(), float(), boolean(), array()Typed values
Lockinglock(), restoreLock()Lock instance
Taggingtags()TaggedCache

Sources: src/Facades/Cache.php20-61

Redis Layer

The Redis facade provides direct access to Redis commands through a connection manager that supports connection pooling and multiple named connections.

Redis Connection Management


Sources: src/Facades/Redis.php9-282

Redis Command Categories

The Redis facade exposes 200+ Redis commands organized by data structure:

Data StructureKey MethodsLine References
Stringsget(), set(), mget(), setnx(), append()29-30 50
HasheshGet(), hSet(), hGetAll(), hmget(), hmset()33-34 125-137
ListslPush(), rPush(), lPop(), rPop(), lrange()150-151 157
SetssAdd(), sMembers(), sInter(), sUnion(), sDiff()188 190-201
Sorted SetszAdd(), zRange(), zRangeByScore(), zRank()244 252-254
Pub/Subsubscribe(), psubscribe(), publish()174-177
Transactionspipeline(), transaction(), multi(), exec()27-28 163 83
Streamsxadd(), xread(), xreadgroup()231 240-241

Sources: src/Facades/Redis.php27-244

Queue Layer

The Queue facade manages asynchronous job processing with support for multiple queue backends, delayed execution, and job lifecycle management.

Queue System Architecture


Sources: src/Facades/Queue.php1-114

Queue Operations and Methods

CategoryMethodsDescription
Job Dispatchpush(), pushOn(), pushRaw()Push jobs to queue
Delayed Jobslater(), laterOn()Schedule jobs for future execution
Bulk Operationsbulk()Push multiple jobs at once
Queue Inspectionsize(), pendingSize(), delayedSize(), reservedSize()Query queue metrics
Connection Managementconnection(), connected(), getConnectionName()Manage queue connections
Worker Lifecyclebefore(), after(), failing(), stopping()Register lifecycle hooks
Testing Supportfake(), assertPushed(), assertPushedOn()Test doubles and assertions

Sources: src/Facades/Queue.php15-72

Queue Fake Testing Pattern

The Queue::fake() method creates a QueueFake instance that intercepts job pushes without executing them:


Sources: src/Facades/Queue.php83-104

Cross-Cutting Features

Transaction Support

The database layer provides comprehensive transaction management:


The transaction() method automatically handles commit, rollback, and retry logic based on exception handling.

Sources: src/Facades/DB.php23-27

Cache Locking

Distributed locks prevent race conditions in cache operations:

MethodPurposeReturn Type
lock(string $name, int $seconds, string $owner)Acquire a lockLock instance
restoreLock(string $name, string $owner)Restore existing lockLock instance

Lock instances provide get(), block(), release(), and forceRelease() methods for fine-grained control.

Sources: src/Facades/Cache.php39-40

Redis Pipelines and Transactions

Redis operations can be batched for performance:


  • pipeline(): Batches commands for network efficiency (non-atomic)
  • transaction(): Executes commands atomically using Redis MULTI/EXEC

Sources: src/Facades/Redis.php27-28

Manager Pattern Implementation

All data persistence services use the Manager pattern to support multiple drivers/connections:

Driver Registration Flow


Each manager maintains:

  • Default driver: Resolved from configuration
  • Connection cache: Reuses driver instances
  • Extension registry: Custom driver support via extend() method
  • Pooling support: Connection pooling for supported drivers

Sources: Referenced from architecture diagrams and manager pattern documentation

Configuration and Container Integration

All facades resolve their underlying services through the PSR-11 container, allowing for:

  1. Service customization: Replace implementations via container bindings
  2. Testing flexibility: Swap services with fakes using Facade::swap()
  3. Lazy initialization: Services instantiated only when accessed
  4. Singleton behavior: Manager instances shared across requests

The container bindings are typically registered by service providers during application bootstrap, mapping interface contracts to concrete implementations.

Sources: src/Facades/DB.php35-38 src/Facades/Cache.php68-71 src/Facades/Redis.php277-280 src/Facades/Queue.php109-112