forked from DesignPatternsPHP/DesignPatternsPHP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PostRepository.php
51 lines (43 loc) · 1.45 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
<?php
declare(strict_types=1);
namespace DesignPatterns\More\Repository;
use OutOfBoundsException;
use DesignPatterns\More\Repository\Domain\Post;
use DesignPatterns\More\Repository\Domain\PostId;
/**
* This class is situated between Entity layer (class Post) and access object layer (Persistence).
*
* 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
{
public function __construct(private Persistence $persistence)
{
}
public function generateId(): PostId
{
return PostId::fromInt($this->persistence->generateId());
}
public function findById(PostId $id): Post
{
try {
$arrayData = $this->persistence->retrieve($id->toInt());
} catch (OutOfBoundsException $e) {
throw new OutOfBoundsException(sprintf('Post with id %d does not exist', $id->toInt()), 0, $e);
}
return Post::fromState($arrayData);
}
public function save(Post $post)
{
$this->persistence->persist([
'id' => $post->getId()->toInt(),
'statusId' => $post->getStatus()->toInt(),
'text' => $post->getText(),
'title' => $post->getTitle(),
]);
}
}