guuzen / resource-composer
应用端连接实现
dev-master
2022-03-08 19:12 UTC
Requires
- php: ^8.0
Requires (Dev)
- phpunit/phpunit: ^9.5
- vimeo/psalm: ^4.13
This package is auto-updated.
Last update: 2024-09-09 00:39:43 UTC
README
这是一个库,其目标是简化来自不同数据源(数据库、API等)的对象(在库中称为资源)连接。
受 https://gist.github.com/fesor/2e1b7cea1b60aa764a9d0da7b7ea2a1d
如何使用它
例如 - 你有一个 Comment,它存储在文档数据库中
final class Comment { public Author $author; public function __construct( public string $id, ) { } }
还有一个 Author,它存储在关系数据库中
final class Author { public function __construct( public string $id, public string $commentId, ) { } }
显然,无法通过标准 SQL 连接轻松连接这些来自不同数据库的 资源,但可以在应用端进行此连接(所谓的应用端连接)。
要连接 Comment 和 Author,需要编写 resolver
final class CommentHasAuthor implements ResourceLink { /** * Loader implementation (which must make actual calls to storage) */ public function loaderClass(): string { return AuthorLoader::class; } /** * Extract values from all $comment->id * Load linked authors by $author->commentId * Write linked authors to respective $comment->author */ public function resolver(): ResourceResolver { return new OneToOne('id', 'commentId', 'author'); } // specify for which resource this resolver is public function resourceClass(): string { return Comment::class; } }
初始化 ResourceComposer 实例并加载相关资源
$links = [new CommentHasAuthor(new Storage())]; $composer = ResourceComposer::create($links, new AuthorLoader()); $composer->loadRelated($comments);
每个 Comment 都将包含相关的 Post