VOOZH about

URL: https://deepwiki.com/hypervel/cache/2.2-repository-pattern

⇱ Repository Pattern | hypervel/cache | DeepWiki


Loading...
Menu

Repository Pattern

Purpose and Scope

The Repository class provides a unified, high-level API for all cache operations in the hypervel/cache system. It acts as an abstraction layer that wraps any concrete Store implementation, adding event dispatching, TTL calculation, type-safe retrieval methods, and convenience patterns like "remember" for lazy computation. This abstraction enables consistent cache interactions regardless of the underlying storage backend (Redis, Database, Swoole, File, etc.).

For information about the underlying storage implementations, see Store Contracts and Cache Stores. For the factory that creates Repository instances, see Cache Manager. For event details, see Event System.

Architecture Overview

The Repository class is the primary interface through which application code interacts with the cache system. It wraps a Store implementation and delegates storage operations to it while providing additional functionality.

Repository Structure


Sources: src/Repository.php37-71

Key Properties

PropertyTypePurpose
storeStoreThe underlying storage backend implementation
eventsEventDispatcherInterfaceEvent dispatcher for cache operation events
defaultintDefault TTL in seconds (3600 by default)
configarrayStore configuration including store name

Sources: src/Repository.php44-62

Core Cache Operations

The Repository provides a comprehensive API for cache operations, with all operations dispatching events for observability.

Reading from Cache


Read Methods:

MethodParametersReturnsDescription
get()string|array $key, mixed $defaultmixedRetrieve single item or multiple items
many()array $keysarrayRetrieve multiple items by keys
getMultiple()iterable $keys, mixed $defaultiterablePSR-16 compatible batch retrieval
has()string|array $keyboolCheck if item exists
missing()string $keyboolCheck if item doesn't exist
pull()string $key, mixed $defaultmixedRetrieve and delete in one operation

Sources: src/Repository.php94-186

Writing to Cache


Write Methods:

MethodParametersReturnsDescription
put()string|array $key, mixed $value, int|null $ttlboolStore item with TTL
set()string $key, mixed $value, int|null $ttlboolAlias for put()
putMany()array $values, int|null $ttlboolStore multiple items
setMultiple()iterable $values, int|null $ttlboolPSR-16 compatible batch write
add()string $key, mixed $value, int|null $ttlboolStore only if key doesn't exist
forever()string $key, mixed $valueboolStore without expiration

Special Behaviors:

  • If $ttl is null, put() calls forever()
  • If $ttl is <= 0, put() calls forget() to delete the key
  • add() delegates to Store::add() if available for atomic operation
  • All methods dispatch corresponding events before and after operation

Sources: src/Repository.php191-330

Deleting from Cache

MethodParametersReturnsDescription
forget()string $keyboolRemove single item
delete()string $keyboolAlias for forget()
deleteMultiple()iterable $keysboolRemove multiple items
clear()-boolFlush entire cache

Events Dispatched:

  • forget(): ForgettingKeyKeyForgotten or KeyForgetFailed
  • clear(): CacheFlushingCacheFlushed or CacheFlushFailed

Sources: src/Repository.php397-443

Remember Pattern

The Repository implements convenience methods for lazy computation and caching - the "remember" pattern.

Remember Methods Flow


Remember Method Variants

MethodSignatureBehavior
remember()remember(string $key, int|null $ttl, Closure $callback)Get from cache or execute callback and store with TTL
rememberForever()rememberForever(string $key, Closure $callback)Get from cache or execute callback and store forever
sear()sear(string $key, Closure $callback)Alias for rememberForever()

Example Usage:


The callback is only executed if the key is not found in cache, making this pattern ideal for expensive computations or database queries.

Sources: src/Repository.php341-394

Type-Safe Retrieval Methods

The Repository provides type-safe getter methods that validate and coerce cached values to specific types, throwing InvalidArgumentException if type validation fails.

Type-Safe Method Matrix


Type Method Details

MethodReturn TypeCoercionValidation
string()stringNoneMust be exactly string
integer()intYesString to int if valid
float()floatYesString to float if valid
boolean()boolNoneMust be exactly bool
array()arrayNoneMust be exactly array

Error Handling:

All type-safe methods throw Hypervel\Cache\Exceptions\InvalidArgumentException with descriptive error messages when type validation fails:

"Cache value for key [user.name] must be a string, integer given."

Sources: src/Repository.php570-665

Atomic Operations

The Repository delegates atomic increment/decrement operations directly to the underlying store.

MethodParametersReturnsDescription
increment()string $key, int $value = 1int|boolIncrement numeric value
decrement()string $key, int $value = 1int|boolDecrement numeric value

These operations are atomic at the store level (e.g., Redis INCR/DECR commands), making them safe for concurrent access.

Sources: src/Repository.php298-312

Array Access Interface

The Repository implements ArrayAccess, enabling array-like syntax for cache operations.

Array Access Mapping


Behavior:

  • offsetSet() uses the repository's default TTL for expiration
  • All operations maintain the same event dispatching as their method equivalents

Sources: src/Repository.php524-563

Event System Integration

The Repository dispatches events for all cache operations, enabling comprehensive observability and logging.

Event Dispatch Timeline


Complete Event List

OperationBefore EventSuccess EventFailure Event
get()RetrievingKeyCacheHitCacheMissed
many()RetrievingManyKeysCacheHit (per key)CacheMissed (per key)
put()WritingKeyKeyWrittenKeyWriteFailed
putMany()WritingManyKeysKeyWritten (per key)KeyWriteFailed (per key)
forget()ForgettingKeyKeyForgottenKeyForgetFailed
clear()CacheFlushingCacheFlushedCacheFlushFailed

All events include the store name and relevant context (keys, values, TTL).

Sources: src/Repository.php124-137 src/Repository.php207-214 src/Repository.php401-409 src/Repository.php432-441 src/Repository.php730-733

Tagged Caching Support

The Repository provides access to tagged caching functionality when the underlying store supports it.

Tag Support Flow


Tag Methods

MethodSignatureReturnsDescription
tags()tags(mixed $names): TaggedCacheTaggedCacheBegin tagged cache operation
supportsTags()supportsTags(): boolboolCheck if store supports tagging

Behavior:

  • Only RedisStore supports tagging in this implementation
  • Throws BadMethodCallException if store doesn't support tags
  • Returns a TaggedCache instance with events and default TTL configured
  • For details on tagged caching, see Cache Tagging

Sources: src/Repository.php445-472

Configuration and Metadata

The Repository provides methods to access and configure its properties.

Configuration Methods

MethodSignaturePurpose
getStore()getStore(): StoreAccess underlying store implementation
getEventDispatcher()getEventDispatcher(): ?EventDispatcherInterfaceGet event dispatcher
setEventDispatcher()setEventDispatcher(EventDispatcherInterface $events): voidSet event dispatcher
getName()getName(): ?stringGet store name from config
getDefaultCacheTime()getDefaultCacheTime(): ?intGet default TTL in seconds
setDefaultCacheTime()setDefaultCacheTime(?int $seconds): staticSet default TTL

Store Name:

The store name comes from $config['store'] and is used in all event dispatching to identify which cache store generated the event.

Sources: src/Repository.php477-522

Extensibility

The Repository is designed for extensibility through the Macroable trait and magic method delegation.

Extensibility Mechanisms


Macro Support

The Macroable trait allows registering custom methods on the Repository class:


Store Method Delegation

The __call magic method delegates unknown method calls to the underlying store, enabling direct access to store-specific functionality:


This delegation pattern is documented in the class docblock: @mixin \Hypervel\Cache\Contracts\Store

Sources: src/Repository.php35-36 src/Repository.php40-42 src/Repository.php74-83

TTL Calculation and Time Handling

The Repository uses the InteractsWithTime trait to handle various TTL formats.

TTL Format Support

Input TypeExampleBehavior
int3600Direct seconds
DateIntervalnew DateInterval('PT1H')Converted to seconds
DateTimeInterfaceCarbon::now()->addHour()Calculates diff from now
nullnullStores forever
<= 0-1 or 0Deletes the key

The getSeconds() method normalizes all TTL formats to integer seconds:

Sources: src/Repository.php14 src/Repository.php39 src/Repository.php714-725

Key Formatting

The itemKey() method provides a hook for key transformation before passing to the store.


In the base Repository, this is a no-op pass-through. However, it can be overridden in subclasses (like TaggedCache) to add prefixes or namespace keys.

Sources: src/Repository.php707-711

PSR-16 SimpleCache Compliance

The Repository implements PSR-16 SimpleCache interface through the CacheContract interface, providing standard cache methods:

PSR-16 MethodRepository MethodNotes
get()get()Direct implementation
set()set() / put()set() is alias
delete()delete() / forget()delete() is alias
clear()clear()Direct implementation
getMultiple()getMultiple()Delegates to many()
setMultiple()setMultiple()Delegates to putMany()
deleteMultiple()deleteMultiple()Iterates forget()
has()has()Direct implementation

Sources: src/Repository.php15 src/Repository.php37 src/Repository.php161-170 src/Repository.php257-260 src/Repository.php412-428