tithely/picomapper

基于PicoDb的最简数据映射器

2.2.0 2023-07-10 21:40 UTC

This package is auto-updated.

Last update: 2024-09-11 02:18:30 UTC


README

PicoMapper是一个基于PicoDb构建的最简数据映射器。

Run Tests

特性

  • 基于PicoDb
  • 无配置文件
  • 许可证:MIT

需求

  • PHP >= 7.3
  • PDO 扩展
  • Sqlite、Mssql、Mysql或Postgresql

文档

安装

composer require tithely/picomapper

设置

use PicoDb\Database;
use PicoMapper\Mapper;
use PicoMapper\Definition;

$db = new Database([...]);
$mapper = new Mapper($db);

概念

定义

为了将数据映射到或从数据库中,必须从定义构建一个映射。定义由一个表、一个主键(一个或多个唯一标识记录的列)、列、子定义(其他定义)和特殊选项组成,这些选项控制着诸如什么被视为已删除记录等事务。

考虑一个具有帖子、评论和作者的博客系统。一个帖子有一个作者和多个评论,一个评论有一个作者。假设帖子、评论和作者有自己的表,一个合适的定义可能看起来如下所示

$author = (new Definition('authors'))
    ->withColumns('name')
    ->withDeletionTimestamp('deleted');

$comment = (new Definition('comments'))
    ->withColumns('content')
    ->withOne($author, 'author', 'id', 'author_id')
    ->withDeletionTimestamp('deleted');

$post = (new Definition('posts'))
    ->withColumns('title', 'content')
    ->withOne($author, 'author', 'id', 'author_id')
    ->withMany($comment, 'comments', 'post_id')
    ->withDeletionTimestamp('deleted');
    
$mapping = $mapper->mapping($post);

Definition的第二个构造函数参数是一个数组,用于在表中唯一标识记录。默认情况下是['id']

可以通过调用withCreationData()withModificationData()分别设置插入和更新时要设置的数据。例如,如果您想向$post定义中添加date_entereddate_modified列,可以按以下方式操作

$post = (new Definition('posts'))
    ->withColumns('title', 'content')
    ->withOne($author, 'author', 'id', 'author_id')
    ->withMany($comment, 'comments', 'post_id')
    ->withCreationData(['date_entered' => gmdate('Y-m-d G:i:s')])
    ->withModificationData(['date_modified' => gmdate('Y-m-d G:i:s')]);
    ->withDeletionTimestamp('deleted');

映射

映射具有与PicoDb的Table类相同的接口。也就是说,您可以对条件进行链式调用,并调用findOne()findAll()来获取记录,或调用insert()update()remove()save()来修改记录。在所有情况下,定义都将被用于智能地返回或接受结构化数组。

在上面的示例中,可以使用以下结构化数组获取或保存帖子,并且所有表关系都会自动遵循。

$post = [
    'id' => 'abc123',
    'author' => [
        'id' => 'zxy321',
        'name' => 'John Doe'
    ],
    'title' => 'Data Mappers Rock',
    'content' => 'They save you time',
    'comments' => [
        [
            'id' => 'def456',
            'post_id' => 'abc123',
            'author' => [
                'id' => 'zxy321',
                'name' => 'John Doe'
            ],
            'content' => 'Did you like my post?'
        ],
        [
            'id' => 'hij789',
            'post_id' => 'abc123',
            'author' => [
                'id' => 'klm012',
                'name' => 'Jane Doe'
            ],
            'content' => 'Nice article!'
        ],
    ]
];

$mapper->save($post);
$saved = $mapper->eq('id', 'abc123')->findOne();

// $saved will be identical in structure to post

钩子

钩子是当映射成功插入、更新或删除记录时可以触发的回调函数。针对映射器注册的钩子将用于它创建的所有顶级映射。

$mapper->registerHook('updated', function ($table, $key, $updated, $original) {
    printf('Table %s (ID: %s) was updated...', $table, implode(':', $key));
});