1、模式定义
Repository 是一个独立的层,介于领域层与数据映射层(数据访问层)之间。它的存在让领域层感觉不到数据访问层的存在,它提供一个类似集合的接口提供给领域层进行领域对象的访问。Repository 是仓库管理员,领域层需要什么东西只需告诉仓库管理员,由仓库管理员把东西拿给它,并不需要知道东西实际放在哪。
Repository 模式是架构模式,在设计架构时,才有参考价值。应用 Repository 模式所带来的好处,远高于实现这个模式所增加的代码。只要项目分层,都应当使用这个模式。
2、UML类图
3、示例代码
Post.php
1 | <?phpnamespace DesignPatterns\More\Repository; class Post{ private $id ; private $title ; private $text ; private $author ; private $created ; public function setId( $id ) { $this ->id = $id ; } public function getId() { return $this ->id; } public function setAuthor( $author ) { $this ->author = $author ; } public function getAuthor() { return $this ->author; } public function setCreated( $created ) { $this ->created = $created ; } public function getCreated() { return $this ->created; } public function setText( $text ) { $this ->text = $text ; } public function getText () { return $this ->text; } public function setTitle( $title ) { $this ->title = $title ; } public function getTitle() { return $this ->title; }}
|
Nach dem Login kopieren
PostRepository.php
1 | <?phpnamespace DesignPatterns\More\Repository; use DesignPatterns\More\Repository\Storage; class PostRepository{ private $persistence ; public function __construct(Storage $persistence ) { $this ->persistence = $persistence ; } public function getById( $id ) { $arrayData = $this ->persistence->retrieve( $id ); if ( is_null ( $arrayData )) { return null; } $post = new Post(); $post ->setId( $arrayData [ 'id' ]); $post ->setAuthor( $arrayData [ 'author' ]); $post ->setCreated( $arrayData [ 'created' ]); $post ->setText( $arrayData [ 'text' ]); $post ->setTitle( $arrayData [ 'title' ]); return $post ; } public function save(Post $post ) { $id = $this ->persistence->persist( array ( 'author' => $post ->getAuthor(), 'created' => $post ->getCreated(), 'text' => $post -> getText (), 'title' => $post ->getTitle() )); $post ->setId( $id ); return $post ; } public function delete (Post $post ) { return $this ->persistence-> delete ( $post ->getId()); }}
|
Nach dem Login kopieren
Storage.php
1 | <?phpnamespace DesignPatterns\More\Repository; interface Storage{ public function persist( $data ); public function retrieve( $id ); public function delete ( $id );}
|
Nach dem Login kopieren
MemoryStorage.php
1 | <?phpnamespace DesignPatterns\More\Repository; use DesignPatterns\More\Repository\Storage; class MemoryStorage implements Storage{ private $data ; private $lastId ; public function __construct() { $this ->data = array (); $this ->lastId = 0; } public function persist( $data ) { $this ->data[++ $this ->lastId] = $data ; return $this ->lastId; } public function retrieve( $id ) { return isset( $this ->data[ $id ]) ? $this ->data[ $id ] : null; } public function delete ( $id ) { if (!isset( $this ->data[ $id ])) { return false; } $this ->data[ $id ] = null; unset( $this ->data[ $id ]); return true; }}
|
Nach dem Login kopieren