<?php
/**
* _ooOoo_
* o8888888o
* 88" . "88
* (| -_- |)
* O\ = /O
* ____/`---'\____
* . ' \\| |// `.
* / \\||| : |||// \
* / _||||| -:- |||||- \
* | | \\\ - /// | |
* | \_| ''\---/'' | |
* \ .-\__ `-` ___/-. /
* ___`. .' /--.--\ `. . __
* ."" '< `.___\_<|>_/___.' >'"".
* | | : `- \`.;`\ _ /`;.`/ - ` : | |
* \ \ `-. \_ __\ /__ _/ .-` / /
* ======`-.____`-.___\_____/___.-`____.-'======
* `=---='
*
* .............................................
* 佛祖保佑 永无BUG
*
* php 技术群:781742505
*/
declare(strict_types=1);
/**
* 相当于 MVC 中,在 M 和 C 之间加了一层。简化了控制器中的代码。
* Class PostRepository
*/
class PostRepository
{
/**
* @var Persistence
*/
private $persistence;
/**
* PostRepository constructor.
*
* @param Persistence $persistence
*/
public function __construct(Persistence $persistence)
{
$this->persistence = $persistence;
}
/**
* @param int $id
*
* @return array
*/
public function findById(int $id)
{
try {
$arrayData = $this->persistence->retrieve($id);
} catch (\OutOfBoundsException $e) {
throw new \OutOfBoundsException(sprintf('not exist',
$id), 0, $e);
}
return $arrayData;
}
}
/**
* Interface Persistence
*/
interface Persistence
{
/**
* @return int
*/
public function generateId(): int;
/**
* @param array $data
*
* @return mixed
*/
public function persist(array $data);
/**
* @param int $id
*
* @return array
*/
public function retrieve(int $id): array;
/**
* @param int $id
*
* @return mixed
*/
public function delete(int $id);
}
/**
* Class InMemoryPersistence
*/
class InMemoryPersistence implements Persistence
{
/**
* @var array
*/
private $data = [];
/**
* @var int
*/
private $lastId = 0;
/**
* @return int
*/
public function generateId(): int
{
$this->lastId++;
return $this->lastId;
}
/**
* @param array $data
*
* @return mixed|void
*/
public function persist(array $data)
{
$this->data[$this->lastId] = $data;
}
/**
* @param int $id
*
* @return array
*/
public function retrieve(int $id): array
{
if (!isset($this->data[$id])) {
throw new \OutOfBoundsException(sprintf('No data found for ID %d',
$id));
}
return $this->data[$id];
}
/**
* @param int $id
*
* @return mixed|void
*/
public function delete(int $id)
{
if (!isset($this->data[$id])) {
throw new \OutOfBoundsException(sprintf('No data found for ID %d',
$id));
}
unset($this->data[$id]);
}
}
/**
* Class PostController
*/
class PostController
{
/**
* @var PostRepository
*/
protected $repository;
/**
* PostController constructor.
*
* @param PostRepository $repository
*/
public function __construct(PostRepository $repository)
{
$this->repository = $repository;
}
/**
* @param $id
*
* @return array
*/
public function find($id)
{
return $this->repository->findById($id);
}
}
$persistence = new InMemoryPersistence();
$id = $persistence->generateId();
$persistence->persist(['name' => '你啊']);
$repository = new PostRepository($persistence);
$return = (new PostController($repository))->find($id);
var_dump($return);
资源库模式
最新推荐文章于 2021-04-01 11:16:09 发布