forked from DesignPatternsPHP/DesignPatternsPHP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PostRepository.php
82 lines (72 loc) · 1.9 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?php
namespace DesignPatterns\More\Repository;
/**
* Repository for class Post
* This class is between Entity layer(class Post) and access object layer(interface Storage).
*
* 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
*/
class PostRepository
{
private $persistence;
public function __construct(Storage $persistence)
{
$this->persistence = $persistence;
}
/**
* Returns Post object by specified id.
*
* @param int $id
*
* @return Post|null
*/
public function getById($id)
{
$arrayData = $this->persistence->retrieve($id);
if (is_null($arrayData)) {
return;
}
$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;
}
/**
* 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(),
'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());
}
}