cpliakas/dynamo-db-odm

DynamoDB 的轻量级 ODM

0.3.5 2014-08-15 14:26 UTC

This package is auto-updated.

Last update: 2024-08-25 12:50:04 UTC


README

Scrutinizer Code Quality Latest Stable Version License

A lightweight, no-frills ODM (Object Document Mapper) for DynamoDB.

注意: 此库仅与 AWS SDK for PHP 的 2.x 版本兼容。SDK 3.x 版本中的更改使其更容易使用,并且此库提供的价值不如以前(这很好,代码更少!)。目前尚不清楚将此库移植到 3.x SDK 是否有用。

为什么?

Amazon 提供了一个连接到 DynamoDB 的 SDK。为什么要在其之上使用 ODM?

  • 允许开发者在代码库中定义数据模型
  • 通过将复杂的数据结构包装在面向对象的 API 中,使代码易于阅读
  • 通过 Symfony 的 EventDispatcher 组件 添加逻辑扩展点
  • 可选地强制执行 实体完整性
  • 促进密码哈希、数据加密、随机字符串生成等

安装

可以通过将 DynamoDB ODM 添加为依赖项到项目的 composer.json 文件中,使用 Composer 安装。

{
    "require": {
        "cpliakas/dynamo-db-odm": "*"
    }
}

有关更详细的安装和使用说明,请参阅 Composer 的文档

用法

定义实体

实体是扩展 Cpliakas\DynamoDb\ODM\Entity 的类,并模拟不同类型的文档。元数据,如表名和哈希/范围键属性,在静态属性中定义,并通过 Cpliakas\DynamoDb\ODM\EntityInterface 中定义的静态方法访问。

namespace Acme\Entity;

use Aws\DynamoDb\Enum\Type;
use Cpliakas\DynamoDb\ODM\Entity;

class Book extends Entity
{
    // The DynanoDB table name
    protected static $table = 'books';

    // The attribute containing the hash key
    protected static $hashKeyAttribute = 'isbn';

    // Optionally set the $rangeKeyAttribute static if appropriate

    // Optionally enforce entity integrity
    protected static $enforceEntityIntegrity = true;

    // Optionally map attributes to data types
    protected static $dataTypeMappings = array(
        'isbn' => Type::STRING,
    );

    // Optionally add attribute setters and getters to taste
    public function setIsbn($isbn)
    {
        $this->setAttribute('isbn', $isbn);
        return $this;
    }

    public function getIsbn()
    {
        return $this->getAttribute('isbn');
    }
}

注意: 其他 ODM 使用 注释 来定义元数据。这种模式可以改进具有大量实体的应用程序的 DX,并在实现适当的缓存时提高性能。然而,此库有意选择使用静态来定义元数据,因为它是对本项目旨在使用的应用程序而言的更轻量级的解决方案。

初始化文档管理器

文档管理器负责实例化实体类并将文档读取/写入到 DynamoDB。

require 'vendor/autoload.php';

use Aws\DynamoDb\DynamoDbClient;
use Cpliakas\DynamoDb\ODM\DocumentManager;

$dynamoDb = DynamoDbClient::factory(array(
    'key'    => '<public-key>',
    'secret' => '<secret-key>',
    'region' => '<aws-region>',
));

$dm = new DocumentManager($dynamoDb);

// Register one or more namespaces that contain entities in order to avoid
// having to pass the fully qualified class names as arguments.
$dm->registerEntityNamesapce('Acme\Entity');

CRUD 操作

创建一个文档。

// Instantiate the entity object to model the new document. "Book" is the
// entity's class name as defined in the "Defining Entities" example above.
$book = $dm->entityFactory('Book')
    ->setHashKey('0-1234-5678-9')
    ->setAttribute('title', 'The Book Title')
    ->setAttribute('author', 'Chris Pliakas')
;

// Documents can also act like arrays
$book['copyright'] = 2014;

// Save the document
$dm->create($book);

// Bulk insert
foreach($books as $book) {
    $dm->createBatch($book);
}
$dm->flush();

读取、更新和删除文档。

// Read the document
$book = $dm->read('Book', '0-1234-5678-9');

// Update the document
$book['title'] = 'Revised title';
$dm->update($book);

// Delete the document
$dm->delete($book);


// Bulk delete
foreach($books as $book) {
    $dm->deleteBatch($book);
}
$dm->flush();

注意: 其他 ODM 在将数据持久化到后端时使用 工作单元模式。由于 DynamoDB 的性质和保持此库轻量级的愿望,我们选择不使用此模式。

复合主键

当实体表使用哈希和范围主键类型时,将数组作为主键参数传递。

// Assume that the "Thread" entity's table uses the hash and range primary key
// type containing the forumName and subject attributes.

// Load the document by the hash and range keys
$book = $dm->read('Thread', array('PHP Libraries', 'Using the DynamoDB ODM'));

查询和扫描命令

您可以将 AWS SDK for PHP 定义的原始数据结构作为第二个参数传递,或使用面向对象的包装器构建搜索条件。以下示例使用面向对象的包装器。

use Aws\DynamoDb\Enum\ComparisonOperator;

// Search for books published after 2010 that don't have the title "Do not read me"
$conditions = Conditions::factory()
    ->addCondition('title', 'Do not read me', ComparisonOperator::NE)
    ->addCondition('copyright', 2010, ComparisonOperator::GT)
;

// Search for books with existing attribute 'extra'
$conditions = Conditions::factory()
    ->addNotNullCondition('extra')
;

$result = $dm->scan('Book', $conditions);

属性转换器

变压器将实体对象设置的属性值转换为其他值。

以下示例基于上面的书籍实体,将作为 \DateTime 对象设置的 created 属性转换为 Unix 时间戳。

namespace Acme\Entity;

use Cpliakas\DynamoDb\ODM\Entity;
use Cpliakas\DynamoDb\ODM\Renderer as Renderer;
use Cpliakas\DynamoDb\ODM\Transformer as Transformer;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

class Book extends Entity
{
    // Set statics here ...

    public function __construct(EventDispatcherInterface $dispatcher, $data = array())
    {
        parent::__construct($dispatcher, $data);
        $this->addTransformer('created', new Transformer\Date());
    }
}

\DateTime 对象设置为 created 属性并创建文档。

$time = new \DateTime();

$book = $dm->entityFactory('Book')
    ->setHashKey('0-1234-5678-9')
    ->setAttribute('created', $time)
;

$dm->create($book);

该值以 Unix 时间戳的形式存储在 DynamoDB 中。

属性渲染器

渲染器将存储在 DynamoDB 中的值转换为在访问时规范化或原生的 PHP 值。

以下示例是上述用例的反例。它将存储在 DynamoDB 中的 Unix 时间戳转换为 \DateTime 对象。

像对变压器所做的那样,将以下语句添加到 Book 对象的构造函数中。

$this->addRenderer('created', new Renderer\Date());

从 DynamoDB 读取文档。访问 created 属性将返回一个 \DateTime 对象。

$book = $dm->read('Book', '0-1234-5678-9');

echo $book['created']->format(\DateTime::ATOM);