forked from DesignPatternsPHP/DesignPatternsPHP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostRepository.php
46 lines (38 loc) · 1.18 KB
/
PostRepository.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?php
namespace DesignPatterns\More\Repository;
/**
* 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
*
* Repository also supports the objective of achieving a clean separation and one-way dependency
* between the domain and data mapping layers
*/
class PostRepository
{
/**
* @var MemoryStorage
*/
private $persistence;
public function __construct(MemoryStorage $persistence)
{
$this->persistence = $persistence;
}
public function findById(int $id): Post
{
$arrayData = $this->persistence->retrieve($id);
if (is_null($arrayData)) {
throw new \InvalidArgumentException(sprintf('Post with ID %d does not exist', $id));
}
return Post::fromState($arrayData);
}
public function save(Post $post)
{
$id = $this->persistence->persist([
'text' => $post->getText(),
'title' => $post->getTitle(),
]);
$post->setId($id);
}
}