walnut / lib_recordstorage

该包最新版本(0.0.4)没有可用的许可信息。

0.0.4 2022-05-13 20:39 UTC

This package is not auto-updated.

Last update: 2024-09-28 07:39:26 UTC


README

基于键值对的记录存储抽象

用法

使用记录存储有多种方式。

使用内存存储和PHP序列化的完整示例

//Create a storage
$storage = new SerializedRecordStorage(
    new PhpArrayDataSerializer,
    new InMemoryKeyValueStorage
);
//An accessor factory for easy access
$accessorFactory = new ArrayDataAccessorFactory($recordStorage);

//Get the product storage
$accessor = $accessorFactory->accessor('products');

//Store some data
$accessor->store('product-id-1', [
    'id' => 'product-id-1', 
    'name' => 'My first product',
    'itemsInStock' => 5
]);

count($accessor->all()); //1

//Fetch the data by key
$accessor->retreive('product-id-1'); //['id' => ..., 'name' => ...]

//Fetch the data by filter
$accessor->byFilter(
    fn(array $entry): bool => $entry['itemsInStock'] > 0
); //[1 record]

//Remove it
$accessor->remove('product-id-1');
//

使用JSON序列化器

//Create a storage
$storage = new SerializedRecordStorage(
    new JsonArrayDataSerializer(
        new JsonSerializer
    ),
    new InMemoryKeyValueStorage
);

使用文件存储

//Create a storage
$storage = new SerializedRecordStorage(
    new JsonArrayDataSerializer(
        new JsonSerializer
    ),
    new InFileKeyValueStorage(
        new PerFileKeyToFileNameMapper(
            baseDir: __DIR__ . '/data',
            fileExtension: 'json'
        )
    )
);

使用缓存存储(强烈推荐)

$storage = new SerializedRecordStorage(/*...*/);
$cacheableStorage = new CacheableRecordStorage($storage)

### 更多适配器和装饰器

  • 事务上下文装饰器
  • Redis适配器
  • ...其他