适用于 PHP 的嵌入式文档数据库。

dev-master 2019-03-21 13:37 UTC

This package is not auto-updated.

Last update: 2024-09-14 19:20:16 UTC


README

License Scrutinizer Code Quality Build Status Total Downloads Latest Stable Version Latest Unstable Version

Ember DB

EmberDb 计划成为 PHP 项目的轻量级、可嵌入的文档数据库实现。

概述

项目包含两部分

  • 需要嵌入到您的应用程序中的库
  • 一个用于直接访问数据库的命令行客户端。

使用方法

通过 composer

$ composer require alexanderduring/ember-db

演示

要试用它,只需克隆存储库,然后在项目主目录中输入

$ php demo/index.php

您将看到创建集合、插入文档和查询文档的一些示例输出。还有一个命令行客户端,您可以使用以下命令启动

$ bin/ember-db --directory=demo/data

功能

设置数据库

要设置数据库,您需要告诉 documentManager 应该在哪里存储和搜索数据库文件 (*.edb)。

$documentManager = new DocumentManager();
$documentManager->setDatabasePath(__DIR__.'/data');

创建集合

要创建集合,只需向其中插入一个文档。

删除集合

要删除整个 'cars' 集合

$documentManager->remove('cars');

插入文档

要将文档插入到集合中

// Set up database
$documentManager = new DocumentManager();
$documentManager->setDatabasePath(__DIR__.'/data');

$car = [
    'license-number' => 'HH-DS 1243',
    'manufacturer' => 'BMW',
    'model' => '325i'
];

// Add an entry to the collection
$documentManager->insert('cars', $car);

要将多个文档插入到集合中

$cars = [
    ['manufacturer' => 'BMW', 'model' => '325i', 'color' => 'blue'],
    ['manufacturer' => 'VW', 'model' => 'Golf', 'color' => 'yellow'],
    ['manufacturer' => 'Fiat', 'model' => 'Punto', 'color' => 'blue']
];
$documentManager->insertMany('cars', $cars);

删除文档

-尚未实现-

查询文档

选择 'cars' 集合中的所有文档

$documents = $documentManager->find('cars');

选择所有蓝色汽车

$filter = ['color' => 'blue'];
$documents = $documentManager->find('cars', $filter);

过滤器

Ember Db 中过滤器的实现受到了 BSON/MongoDB 中使用的查询运算符的启发。

当前可用的过滤运算符

  • $gt (大于)
  • $gte (大于或等于)
  • $lt (小于)
  • $lte (小于或等于)
  • $ne (不等于)
  • $elementMatch (匹配数组中的至少一个元素)

示例

查询所有发动机功率超过 36 kw 的汽车

$filter = ['engine' => [
    'powerInKw' => ['$gt' => 36]
]];
$documents = $documentManager->find('cars', $filter);

查询所有制造商不是菲亚特的汽车

$filter = ['manufacturer' => ['$ne' => 'Fiat']];
$documents = $documentManager->find('cars', $filter);

实现构思

可能有一个 "Manager" 类作为访问数据库的唯一入口点。需要决定这个类是否应该将文档作为数组或对象返回。

数组

优点

  • 数组没有方法,因此不可能将业务逻辑添加到行对象中。在领域模型层中实现此类类有更强的需求。

对象

优点

  • 访问器方法的实现提供了在每次设置/获取事件上执行操作的钩子。
  • 由于文档的无结构性质,其中一些可能有 "foo" 条目,而另一些则没有。为了检查这一点,您需要进行多次调用 array_key_exists 来遍历文档的结构。具有提供辅助方法以轻松完成此任务的文档对象是一个优点。
class document
{
    private $data;



    public __construct($jsonData = null)
    {
        $this->data = is_null($jsonData) ? array() : json_decode($jsonData, true);
    }



    public function has($path)
    {
        // Check if array key decribed by $path exists.
    }



    public function get($path)
    {
        // Return array value indexed by array key decribed by $path.
    }



    public function toJson()
    {
        return json_encode($this->data);
    }
}