tomkyle/repository-persistence

Repository-and-Persistence 设计模式脚手架

1.0.1 2024-08-28 18:10 UTC

This package is auto-updated.

Last update: 2024-08-28 18:10:36 UTC


README

Packagist PHP version PHP Composer Software License

Repository-and-Persistence 设计模式脚手架。

安装

$ composer require tomkyle/repository-persistence

设置

该存储库需要一个持久化。

<?php

use tomkyle\RepositoryPersistence\Repositories\Repository;
use tomkyle\RepositoryPersistence\Persistence;

$repo = new Repository(
	new Persistence\JsonFilePersistence('path/to/json')
);

在这个示例中,持久化在目录 path/to/json 上工作,其中项目以它们的ID命名的JSON文件中存储。 —— 示例:john-doe.json

{
  "age": 30,
  "city": "New York",
  "name": "John Doe"
}

使用方法

获取项目。此方法可能抛出 \OutOfBoundsException

try {
  $person = $repo->get('john-doe');
  print_r($person);
} 
catch (\OutOfBoundsException) {
  // Not found
}

输出将如下

Array  (
  [age] => 30
  [city] => New York
  [name] => John Doe
)

根据标准查找一个项目。此方法可能返回 null

$repo->findOneBy([
  'name' => 'John'
]);  

获取所有项目

$repo->findAll();

根据标准查找项目

$repo->findBy([
  'color' => 'blue'
]);

更新项目

$saved = $repo->save(['id' => 43, 'name' => 'John']));

删除项目

$repo->delete(43);

创建新项目

$saved = $repo->save(['name' => 'Angie']));

如果您需要在您的应用程序控制器中预先获得新ID,例如将客户端重定向到新资源,您可以从存储库中获取新ID。它看起来就像更新一样,但 Repository 实现将确定项目是否需要创建或更新。

$new_id = $repo->getNextId();
$repo->save(['id' => $new_id, 'name' => 'Angie']));

持久化

在存储库内部,Persistence 实际上管理数据存储。

实例化

<?php
use tomkyle\RepositoryPersistence\Repositories;
use tomkyle\RepositoryPersistence\Persistence;

$persistence = new Persistence\JsonFilePersistence('path/to/json');
$persistence = new Persistence\YamlFilePersistence('path/to/yaml');

方法API

特殊实现

FrontmatterFilePersistence

如果您的JSON或YAML文件有frontmatters

$persistence = new Persistence\FrontmatterFilePersistence(
	new Persistence\JsonFilePersistence('path/to/json')
);

PersistenceChain

$persistence = new Persistence\PersistenceChain(
	new Persistence\JsonFilePersistence('path/to/json'),
	new Persistence\YamlFilePersistence('path/to/yaml')
);

InMemoryPersistence

一个可以写入和读取的空 Persistence

$persistence = new Persistence\InMemoryPersistence();

NoPersistence

Persistence 的模拟实现,它模拟数据持久化操作而不实际存储数据。请注意,read 方法将始终抛出 \OutOfBoundsException,因为它不包含任何数据!

$persistence = new Persistence\NoPersistence();

Repository

存储库是您在应用程序中使用的。

<?php
use tomkyle\RepositoryPersistence\Repositories\Repository;
use tomkyle\RepositoryPersistence\Persistence; 

// Feed a persistence to the repo:
$persistence = new Persistence\InMemoryPersistence();
$repository = new Repository($persistence)

方法API

开发

安装要求

$ composer install
$ npm install

监视源代码并运行各种测试

这将监视 src/tests/ 目录中的更改并运行一系列测试

  1. 使用 PHPUnit 找到并运行相应的单元测试。
  2. 使用 phpstan 找到可能的错误和文档问题。
  3. 使用 Rector 分析代码风格并提供有关新语法的提示。
$ npm run watch

运行所有测试

根据您的喜好选择

$ npm run phpunit
$ composer test