本文章为各位介绍一篇关于php设计模式之repository资源库模式学习笔记了,希望这篇文章可以为各位带来帮助,具体如下。
1、模式定义
repository 是一个独立的层,介于领域层与数据映射层(数据访问层)之间。它的存在让领域层感觉不到数据访问层的存在,它提供一个类似集合的接口提供给领域层进行领域对象的访问。repository 是仓库管理员,领域层需要什么东西只需告诉仓库管理员,由仓库管理员把东西拿给它,并不需要知道东西实际放在哪。
repository 模式是架构模式,在设计架构时,才有参考价值。应用 repository 模式所带来的好处,远高于实现这个模式所增加的代码。只要项目分层,都应当使用这个模式。
2、uml类图
3、示例代码
post.php
id = $id;
}
/**
* @return int
*/
public function getid()
{
return $this->id;
}
/**
* @param string $author
*/
public function setauthor($author)
{
$this->author = $author;
}
/**
* @return string
*/
public function getauthor()
{
return $this->author;
}
/**
* @param \datetime $created
*/
public function setcreated($created)
{
$this->created = $created;
}
/**
* @return \datetime
*/
public function getcreated()
{
return $this->created;
}
/**
* @param string $text
*/
public function settext($text)
{
$this->text = $text;
}
/**
* @return string
*/
public function gettext()
{
return $this->text;
}
/**
* @param string $title
*/
public function settitle($title)
{
$this->title = $title;
}
/**
* @return string
*/
public function gettitle()
{
return $this->title;
}
}
postrepository.php
persistence = $persistence;
}
/**
* 通过指定id返回post对象
*
* @param int $id
* @return post|null
*/
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;
}
/**
* 保存指定对象并返回
*
* @param post $post
* @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;
}
/**
* 删除指定的 post 对象
*
* @param post $post
* @return bool
*/
public function delete(post $post)
{
return $this->persistence->delete($post->getid());
}
}
storage.php
lastid = 0;
}
/**
* {@inheritdoc}
*/
public function persist($data)
{
$this->data[++$this->lastid] = $data;
return $this->lastid;
}
/**
* {@inheritdoc}
*/
public function retrieve($id)
{
return isset($this->data[$id]) ? $this->data[$id] : null;
}
/**
* {@inheritdoc}
*/
public function delete($id)
{
if (!isset($this->data[$id])) {
return false;
}
$this->data[$id] = null;
unset($this->data[$id]);
return true;
}
}