porrebskk/simple-php-document-store

1.1.1 2018-06-26 18:23 UTC

This package is not auto-updated.

Last update: 2024-09-29 05:08:24 UTC


README

SimplePhpDocumentStore 是一个简单的文档存储(即存储 php 数组的术语),它底层运行 sql。它还提供了一个使用从文档中提取的路径的查询组件。查询部分是通过在数据库中存储文档时进行额外操作来解决的(将所有唯一路径作为单独的值存储)。

安装

composer require porebskk/simple-php-document-store

功能

  • 通过 DBAL 支持多种数据库平台
  • JSON-Path 查询构建器

用法

初始化

//Setting up the DbalAdapter, we are using here Sqlite in memory mode
//requires the sqlite extension to be enabled in the used php.ini file
$connectionParams = ['url' => 'sqlite:///:memory:'];
$conn = DriverManager::getConnection($connectionParams);
$conn->exec('PRAGMA foreign_keys = ON');
$dbalAdapter = new DbalAdapter($conn);

//this is only required once for persistence storages
$dbalAdapter->initDataStructure();

存储

$document = [
    'person' => [
        'head' => [
            'nose' => 'big',
            'eyes' => 'blue',
        ],
    ],
];

$documentId = $dbalAdapter->store($document);

按 ID 查询

$documentId = $dbalAdapter->store($document);

$document = $dbalAdapter->searchById($documentId);

使用 QueryObject 查询

$query = new Query();
//Finding document where the JSON Path "person.head.eyes" is either red or orange
//Allowed operators depend on the adapter implementation
//for DBAL see the ExpressionBuilder::* constants
$query->whereAnd(
    (new OrStatement())->add(
        new WhereStatement('person.head.eyes', '=', 'red'),
        new WhereStatement('person.head.eyes', '=', 'orange')
    )
);

$documents = $dbalAdapter->searchByQuery($query);

//It is possible to wrap AND/OR Statement as deep as possible
$query->whereAnd(
    (new OrStatement())->add(
        new WhereStatement('person.head.eyes', '=', 'blue'),
        (new AndStatement())->add(
            new WhereStatement('person.head.eyes', '=', 'orange'),
            new WhereStatement('person.character.crazy', '=', 'yes')
        )
    ),
    new WhereStatement('person.feet', '=', 'big')
);

更新文档

$dbalAdapter->update($documentId, $updatedDocument);

限制返回文档的数量

$query = (new Query())->limit(5);

$maximumOf5Documents = $dbalAdapter->searchByQuery($query);

高级用法

存储包含数组数据的文档并查询它们

$document = [
    'friends' => [
        ['person' => ['name' => 'Bob', 'age' => 26]],
        ['person' => ['name' => 'Alice', 'age' => 25]],
    ],
];

$dbalAdapter->store($document);

//Following paths will be extracted from the array:
//'friends.person.name' => 'Bob',
//'friends.person.age' => 26
//'friends.person.name' => 'Alice'
//'friends.person.age' => 25

//Now we query the data
$query = new Query();
$query->whereAnd(
    new WhereStatement('friends.person.age', '<', '30')
);

$documents = $dbalAdapter->searchByQuery($query);