PHPackages                             liyuze/php-data-bag - 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. liyuze/php-data-bag

ActiveLibrary[Caching](/categories/caching)

liyuze/php-data-bag
===================

Cache the execution results to prevent multiple executions.

1.0.0(3y ago)03MITPHPPHP ^7.4|^8.0

Since May 9Pushed 3y ago1 watchersCompare

[ Source](https://github.com/liyuze/php-data-bag)[ Packagist](https://packagist.org/packages/liyuze/php-data-bag)[ Docs](https://github.com/liyuze/php-data-bag)[ RSS](/packages/liyuze-php-data-bag/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (1)Versions (2)Used By (0)

php-data-bag
============

[](#php-data-bag)

在单次请求中缓存执行结果以防止高耗时程序多次执行。

[![Latest Version on Packagist](https://camo.githubusercontent.com/d8860edb51573b4fd3e61fdbc0664ccdc00410b71662a4c968b189fbed6dbe63/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6c6979757a652f7068702d646174612d6261672e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/liyuze/php-data-bag)[![Total Downloads](https://camo.githubusercontent.com/14b1107cd817fea7217eca84a51fe91b32e7abeab7d8b85689605d56c4173ff5/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6c6979757a652f7068702d646174612d6261672e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/liyuze/php-data-bag)[![GitHub Actions](https://github.com/liyuze/php-data-bag/actions/workflows/main.yml/badge.svg)](https://github.com/liyuze/php-data-bag/actions/workflows/main.yml/badge.svg)

主要适用于数据库查询、文件操作等高耗时方法的场景。

安装
--

[](#安装)

通过 composer 安装此包:

```
composer require liyuze/php-data-bag
```

用法
--

[](#用法)

```
$bag = new DataBag();

$cacheKey = 'cache_key';
$callable = function () {
    //数据库查询、耗时运算
    return 'result';
}

//运行 callable 并将执行结果放入背包
$bag->pickUp('cache_key', $callable);   //result

//获取背包中某 key 对应的值
$bag->take($cacheKey);  //result

//获取背包中某 key 对应的值，并删除掉改数据项
$bag->throw($cacheKey);  //result

//直接将结果放入到背包中
$bag->put($cacheKey, 123);    //void

//判断背包中是否存在某个 key
$bag->exists($cacheKey); //true
$bag->exists('k1', 'k2'); //指定的 keys 都存在时返回 true
$bag->existsAny('k1', 'k2'); //指定的 keys 任何一个存在时返回 true

//清空背包
$bag->clear(); //void
```

### 数组类型支持

[](#数组类型支持)

```
//设置单个元素
public function putItem(string $key, string $subKey, mixed $value): void;

//取出单个元素
public function takeItem(string $key, string $subKey): mixed;

//取出单个元素，并丢掉该元素
public function throwItem(string $key, string $subKey): mixed;

//判断指定的一些子元素是否都存在
public function existsItem(string $key, string ...$subKeys): bool;

//判断指定的一些子元素是否至少存在一个
public function existsAnyItem(string $key, string ...$subKeys): bool;

//合并一个或多个新的数组到旧元素上
public function mergeItems(string $key, array ...$arrays): array;
```

### 拦截器

[](#拦截器)

数据背包通过 `拦截器` 来判断一个值是否为有效值，无效值将被丢弃，不被缓存。默认配置的 `NullInspector` 拦截器，当值为 `null`时将不进行缓存。

可用的拦截器：

- `NullInspector` `=== null` 拦截器。
- `EmptyInspector` `empty()` 拦截器。
- `InInspector` `in_array()` （强类型对比）拦截器。
- `ClosureInspector` 自定义类型拦截器。
- `NothingnessInspector` 无限制拦截器（任何类型都是有效值）。

设置拦截器有两种方式：

一、全局设置

```
$bag = new DataBag();
$bag->setInspector(new \Liyuze\PhpDataBag\Inspectors\EmptyInspector());
```

二、临时设置

```
$bag->pickUp('cacheKey', fn ()=>0, new \Liyuze\PhpDataBag\Inspectors\\Liyuze\PhpDataBag\Inspectors\EmptyInspector());
```

### 逃脱值

[](#逃脱值)

`可逃脱值` 不能被缓存。

```
$bag->pickUp('cacheKey', fn () => {
    return new \Liyuze\PhpDataBag\Proxies\EscapeProxy(5);
});
$bag->exists('cacheKey'); //false
```

> 与拦截器的区别
>
> 拦截器：适用于统一设置的缓存拦截器，针对所有被缓存的值进行检查。
> 可逃脱值：适用于特殊情况，进行针对当前要缓存的值有效。优先级比拦截器高，可以覆盖拦截器的缓存规则。

### 避难值

[](#避难值)

`避难值` 将跳过检查器的拦截，进行缓存。

```
$bag->setInspector(new \Liyuze\PhpDataBag\Inspectors\EmptyInspector());
$bag->pickUp('cacheKey', fn ()=> {
    return new \Liyuze\PhpDataBag\Proxies\RefugeProxy(0);
});
$bag->exists('cacheKey'); //true
```

> 与拦截器的区别
>
> 拦截器：适用于统一设置的缓存拦截器，针对所有被缓存的值进行检查。
> 避难值：适用于特殊情况，进行针对当前要缓存的值有效。优先级比`拦截器`高，比`逃脱值`低。

### 贪婪模式

[](#贪婪模式)

在贪婪模式下，`pickUp` 和 `pickUpArr` 中的 `callable` 总是会执行，这在排查系统性能时很有用。

开启方式有两种：

一、全局开启

```
$bag->setIsGreedy(true);
```

二、局部开启

```
$bag->runInGreedyMode(function () {
    //在贪婪模式开启中执行程序
});
```

### Testing

[](#testing)

```
composer test
```

### Changelog

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

### Security

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Yuze Li](https://github.com/liyuze)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

PHP Package Boilerplate
-----------------------

[](#php-package-boilerplate)

This package was generated using the [PHP Package Boilerplate](https://laravelpackageboilerplate.com)by [Beyond Code](http://beyondco.de/).

###  Health Score

22

—

LowBetter than 22% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity3

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

1102d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/affde44e5a0df86c5ab089ed20dd4c7dcb6958e9fcbbb0aebd3f02cf83717ba4?d=identicon)[liyuze](/maintainers/liyuze)

---

Top Contributors

[![liyuze](https://avatars.githubusercontent.com/u/4597092?v=4)](https://github.com/liyuze "liyuze (2 commits)")

---

Tags

cachedata-bagphp-data-bag

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/liyuze-php-data-bag/health.svg)

```
[![Health](https://phpackages.com/badges/liyuze-php-data-bag/health.svg)](https://phpackages.com/packages/liyuze-php-data-bag)
```

###  Alternatives

[psr/simple-cache

Common interfaces for simple caching

8.1k727.3M2.1k](/packages/psr-simple-cache)[psr/cache

Common interface for caching libraries

5.2k686.9M1.3k](/packages/psr-cache)[react/cache

Async, Promise-based cache interface for ReactPHP

444112.4M40](/packages/react-cache)[beste/in-memory-cache

A PSR-6 In-Memory cache that can be used as a fallback implementation and/or in tests.

2512.2M6](/packages/beste-in-memory-cache)[anahkiasen/flatten

A package for the Illuminate framework that flattens pages to plain HTML

33313.0k](/packages/anahkiasen-flatten)[rtcamp/nginx-helper

Cleans nginx's fastcgi/proxy cache or redis-cache whenever a post is edited/published. Also provides cloudflare edge cache purging with Cache-Tags.

23817.0k1](/packages/rtcamp-nginx-helper)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
