mirror of
https://github.com/DesignPatternsPHP/DesignPatternsPHP.git
synced 2025-08-05 06:27:25 +02:00
PHP7 More
This commit is contained in:
@@ -3,7 +3,7 @@
|
||||
namespace DesignPatterns\More\Repository;
|
||||
|
||||
/**
|
||||
* This class is between Entity layer (class Post) and access object layer (interface Storage).
|
||||
* This class is situated between Entity layer (class Post) and access object layer (MemoryStorage).
|
||||
*
|
||||
* Repository encapsulates the set of objects persisted in a data store and the operations performed over them
|
||||
* providing a more object-oriented view of the persistence layer
|
||||
@@ -13,67 +13,34 @@ namespace DesignPatterns\More\Repository;
|
||||
*/
|
||||
class PostRepository
|
||||
{
|
||||
/**
|
||||
* @var MemoryStorage
|
||||
*/
|
||||
private $persistence;
|
||||
|
||||
public function __construct(Storage $persistence)
|
||||
public function __construct(MemoryStorage $persistence)
|
||||
{
|
||||
$this->persistence = $persistence;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns Post object by specified id.
|
||||
*
|
||||
* @param int $id
|
||||
*
|
||||
* @return Post|null
|
||||
*/
|
||||
public function getById($id)
|
||||
public function findById(int $id): Post
|
||||
{
|
||||
$arrayData = $this->persistence->retrieve($id);
|
||||
|
||||
if (is_null($arrayData)) {
|
||||
return;
|
||||
throw new \InvalidArgumentException(sprintf('Post with ID %d does not exist'));
|
||||
}
|
||||
|
||||
$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;
|
||||
return Post::fromState($arrayData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Save post object and populate it with id.
|
||||
*
|
||||
* @param Post $post
|
||||
*
|
||||
* @return Post
|
||||
*/
|
||||
public function save(Post $post)
|
||||
{
|
||||
$id = $this->persistence->persist(array(
|
||||
'author' => $post->getAuthor(),
|
||||
'created' => $post->getCreated(),
|
||||
$id = $this->persistence->persist([
|
||||
'text' => $post->getText(),
|
||||
'title' => $post->getTitle(),
|
||||
));
|
||||
]);
|
||||
|
||||
$post->setId($id);
|
||||
|
||||
return $post;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes specified Post object.
|
||||
*
|
||||
* @param Post $post
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function delete(Post $post)
|
||||
{
|
||||
return $this->persistence->delete($post->getId());
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user