PHP code example of liyuze / php-data-bag

1. Go to this page and download the library: Download liyuze/php-data-bag library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

liyuze / php-data-bag example snippets


$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;

$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

$bag->setIsGreedy(true);

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