dealnews/repository

处理中/请求数据仓库

4.0.0 2024-02-12 22:51 UTC

This package is auto-updated.

Last update: 2024-09-13 00:25:12 UTC


README

这个库提供了一个通用的数据仓库,它能够通过已注册的回调按需加载数据,并确保在数据仓库对象存在期间数据只加载一次。这对于应用程序的不同部分需要使用相同数据但用于不同目的非常有用。

它还支持通过仓库写入数据。

用法

基本示例

<?php

$repo = new \DealNews\Repository\Repository();
$dao = new My_Data_Object();

// assuming $dao has a load() method that takes
// an array of ids
$repo->register("my_data", [$dao, "load"]);

// $data is returned as an array with keys matching the ids passed
// in to the getMulti() method
$data = $repo->getMulti("my_data", [1,2,3]);

// Or, the get method can be used to return just on object
$obj = $repo->get("my_data", 1);

写入

<?php

$repo = new \DealNews\Repository\Repository();
$dao = new My_Data_Object();
// assuming $dao has a load() method that takes
// an array of ids
$repo->register("my_data", [$dao, "load"], [$dao, "save"]);

$foo = new Foo();
$foo->name = "example";

// save returns the data (possibly updated by the storage later)
// that it is sent
$foo = $repo->save("my_data", $foo);

我们的用例

在DealNews,我们使用带有已注册处理器的Repository单例为应用程序。

以下是一个构建Repository对象的示例。

<?php

namespace MyAPP;

class DataRepository {
    public static function init() {
        static $repo;
        if (empty($repo)) {
            $repo = new \DealNews\Repository\Repository();

            // All of these handlers are only setting read callbacks
            // There is no writing for this repository.

            $book = new Book();
            $repo->register("book", [$book, "fetch"]);

            $author = new Author();
            $repo->register("author", [$author, "fetch"]);

        }
        return $repo;
    }
}