PHPackages                             hwlowell/request-cache - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Caching](/categories/caching)
4. /
5. hwlowell/request-cache

ActiveLibrary[Caching](/categories/caching)

hwlowell/request-cache
======================

A Laravel cache package for request caching with Redis and local cache support

1.0.2(2mo ago)1199↑133.3%MITPHPPHP &gt;=8.2

Since Feb 3Pushed 2mo agoCompare

[ Source](https://github.com/lowelllab/hwlowell-request-cache)[ Packagist](https://packagist.org/packages/hwlowell/request-cache)[ Docs](https://github.com/lowelllab/hwlowell-request-cache)[ RSS](/packages/hwlowell-request-cache/feed)WikiDiscussions master Synced 3w ago

READMEChangelog (2)Dependencies (10)Versions (7)Used By (0)

RequestCache Laravel Package
============================

[](#requestcache-laravel-package)

A Laravel cache package for request caching with Redis and local cache support.

Features
--------

[](#features)

- Redis-based caching with local cache fallback
- Cache tagging support
- Request parameter filtering and sanitization
- Cache statistics and monitoring
- Distributed lock support to prevent cache stampedes
- Cache warming functionality
- Encryption support for sensitive data
- Redis connection pool management
- Batch operations support
- Cache version control

Requirements
------------

[](#requirements)

- PHP 7.4+
- Laravel 8.75+
- Redis server (for primary caching)

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require hwlowell/request-cache
```

Configuration
-------------

[](#configuration)

The package will automatically register its service provider. You can publish the configuration file if needed:

```
php artisan vendor:publish --provider="HwlowellRequestCache\RequestCacheServiceProvider" --tag="config"
```

Usage
-----

[](#usage)

### Basic Usage

[](#basic-usage)

```
use HwlowellRequestCache\RequestCache;

//Create a new instance
$cache = new RequestCache();

//Set cache
$cache->set('users', ['id' => 1], ['name' => 'John Doe'], 3600);

//Get cache
$user = $cache->get('users', ['id' => 1]);

//Delete cache
$cache->delete('users', ['id' => 1]);

//Clear all cache for a gateway
$cache->clearGateway('users');

//Clear cache by tags
$cache->clearTags(['users', 'profiles']);

//Clear all cache
$cache->clearAll();
```

### Using the Decorator Pattern

[](#using-the-decorator-pattern)

```
use HwlowellRequestCache\RequestCache;

$cache = new RequestCache();

//Cache the result of a callback
$data = $cache->remember('users', ['id' => 1], function () {
    //Expensive operation, e.g., API call or database query
    return User::find(1);
}, 3600);
```

### Using the Facade

[](#using-the-facade)

```
use RequestCache;

//Set cache
RequestCache::set('users', ['id' => 1], ['name' => 'John Doe']);

//Get cache
$user = RequestCache::get('users', ['id' => 1]);
```

### Cache Monitoring

[](#cache-monitoring)

```
use HwlowellRequestCache\CacheMonitor;

$monitor = new CacheMonitor();

//Get cache statistics
$stats = $monitor->getStats();

//Get cache key distribution
$distribution = $monitor->getKeyDistribution();

//Get cache usage trend
$trend = $monitor->getTrend(7); // 7 days

//Get health status
$status = $monitor->getHealthStatus();
```

Advanced Usage
--------------

[](#advanced-usage)

### 1. 基本缓存操作

[](#1-基本缓存操作)

#### 设置缓存

[](#设置缓存)

```
//设置缓存，默认过期时间
$cache->set('user_profile', ['user_id' => 1], [
    'name' => '张三',
    'age' => 30,
    'email' => 'zhangsan@example.com'
]);

//设置缓存，自定义过期时间（10分钟）
$cache->set('user_profile', ['user_id' => 1], [
    'name' => '张三',
    'age' => 30,
    'email' => 'zhangsan@example.com'
], 10 * 60);
```

#### 获取缓存

[](#获取缓存)

```
//获取缓存
$userProfile = $cache->get('user_profile', ['user_id' => 1]);

if ($userProfile) {
    echo "缓存命中：" . $userProfile['name'];
} else {
    echo "缓存未命中";
}
```

#### 删除缓存

[](#删除缓存)

```
//删除缓存
$cache->delete('user_profile', ['user_id' => 1]);
```

### 2. 批量操作

[](#2-批量操作)

#### 批量获取缓存

[](#批量获取缓存)

```
//批量获取缓存
$results = $cache->mget([
    ['user_profile', ['user_id' => 1]],
    ['user_profile', ['user_id' => 2]],
    ['user_profile', ['user_id' => 3]]
]);

foreach ($results as $index => $userProfile) {
    if ($userProfile) {
        echo "用户 " . ($index + 1) . "：" . $userProfile['name'] . "\n";
    } else {
        echo "用户 " . ($index + 1) . " 缓存未命中\n";
    }
}
```

#### 批量设置缓存

[](#批量设置缓存)

```
//批量设置缓存
$results = $cache->mset([
    ['user_profile', ['user_id' => 1], ['name' => '张三', 'age' => 30], 600],
    ['user_profile', ['user_id' => 2], ['name' => '李四', 'age' => 25], 600],
    ['user_profile', ['user_id' => 3], ['name' => '王五', 'age' => 35], 600]
]);

print_r($results); //[true, true, true]
```

### 3. 缓存装饰器（Remember）

[](#3-缓存装饰器remember)

缓存装饰器是一个非常实用的功能，它会先尝试从缓存获取数据，如果缓存未命中，则执行回调函数获取数据并自动存入缓存。

```
//使用缓存装饰器
$userProfile = $cache->remember('user_profile', ['user_id' => 1], function() {
    //这里是获取数据的逻辑，例如从数据库查询
    echo "执行回调函数获取数据\n";
    return [
        'name' => '张三',
        'age' => 30,
        'email' => 'zhangsan@example.com',
        'timestamp' => time()
    ];
}, 10 * 60); //10分钟过期

echo "用户信息：" . $userProfile['name'] . " (" . date('Y-m-d H:i:s', $userProfile['timestamp']) . ")\n";

//再次调用，会从缓存获取
$userProfile = $cache->remember('user_profile', ['user_id' => 1], function() {
    echo "执行回调函数获取数据\n";
    return [
        'name' => '张三',
        'age' => 30,
        'email' => 'zhangsan@example.com',
        'timestamp' => time()
    ];
});

echo "用户信息：" . $userProfile['name'] . " (" . date('Y-m-d H:i:s', $userProfile['timestamp']) . ")\n";
```

### 4. 缓存标签

[](#4-缓存标签)

缓存标签可以帮助你对缓存进行分组管理，方便批量清除特定分组的缓存。

```
//使用缓存标签
$cache->tags('user', 'profile')->set('user_profile', ['user_id' => 1], [
    'name' => '张三',
    'age' => 30
]);

$cache->tags('user', 'settings')->set('user_settings', ['user_id' => 1], [
    'theme' => 'dark',
    'language' => 'zh-CN'
]);

//清除特定标签的缓存
$cache->clearTags('user'); //清除所有带有 'user' 标签的缓存
//或者
$cache->clearTags(['user', 'profile']); //清除同时带有 'user' 和 'profile' 标签的缓存
```

### 5. 缓存清除

[](#5-缓存清除)

#### 清除指定网关的缓存

[](#清除指定网关的缓存)

```
//清除指定网关的缓存（当前版本）
$cache->clearGateway('user_profile');

//清除指定网关的所有版本缓存
$cache->clearGateway('user_profile', true);
```

#### 清除所有缓存

[](#清除所有缓存)

```
//清除所有缓存（当前版本）
$cache->clearAll(false);

//清除所有版本的缓存
$cache->clearAll(true);
```

### 6. 缓存统计

[](#6-缓存统计)

```
//启用缓存统计
$cache->enableStats(true);

//执行一些缓存操作
$cache->remember('test', ['id' => 1], function() {
    return ['data' => 'test'];
});

//获取缓存统计信息
$stats = $cache->getStats();

print_r($stats);
/*
输出示例：
Array
(
    [hits] => 0
    [misses] => 1
    [today_hits] => 0
    [today_misses] => 1
    [hit_rate] => 0
)
*/
```

### 7. 缓存预热

[](#7-缓存预热)

缓存预热可以在系统启动或低峰期预先加载缓存数据，提高系统响应速度。

```
//缓存预热
$cache->warm('user_profile', ['user_id' => 1], function() {
    //从数据库或其他数据源获取数据
    return [
        'name' => '张三',
        'age' => 30,
        'email' => 'zhangsan@example.com'
    ];
}, 3600); //1小时过期

//批量预热多个用户的缓存
$userIds = [1, 2, 3, 4, 5];
foreach ($userIds as $userId) {
    $cache->warm('user_profile', ['user_id' => $userId], function() use ($userId) {
        //从数据库获取用户信息
        return [
            'user_id' => $userId,
            'name' => '用户' . $userId,
            'age' => 20 + $userId,
            'email' => 'user' . $userId . '@example.com'
        ];
    });
}
```

### 8. 高级配置选项

[](#8-高级配置选项)

#### 版本控制

[](#版本控制)

```
//设置缓存版本
$cache->version('2.0');

//生成的缓存键会包含版本信息
$key = $cache->generateKey('user_profile', ['user_id' => 1]);
echo "缓存键：" . $key . "\n";
```

#### 数据加密

[](#数据加密)

```
//启用/禁用数据加密
$cache->encryptData(true); //启用加密
$cache->encryptData(false); //禁用加密
```

#### 缓存大小限制

[](#缓存大小限制)

```
//设置缓存大小限制（512KB）
$cache->sizeLimit(512 * 1024);
```

#### 强制参数校验

[](#强制参数校验)

```
//启用/禁用强制参数校验
$cache->setForceValidate(true); //启用
$cache->setForceValidate(false); //禁用
```

Complete Usage Examples
-----------------------

[](#complete-usage-examples)

### Example 1: User Information Cache

[](#example-1-user-information-cache)

```
