-
Notifications
You must be signed in to change notification settings - Fork 2
/
PrototypeExt.php
104 lines (89 loc) · 2.33 KB
/
PrototypeExt.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
<?php
namespace DesignPatterns\Creational;
use DateTime;
/**
* Page class has lots of private fields, which will be copied to the cloned object
*/
class Page
{
private $title;
private $body;
private $comments = [];
private $date;
/** @var Author */
private $author;
public function __construct($title, $body, $author)
{
$this->title = $title;
$this->body = $body;
$this->author = $author;
$this->author->addToPage($this);
$this->date = new DateTime();
}
public function addComment($comment)
{
$this->comments[] = $comment;
}
/**
* Magic method creates a copy of an object.
* Here we can control what data should be copied to the cloned object
*/
public function __clone()
{
$this->title = $this->title . '(copy)';
$this->author->addToPage($this);
$this->comments = [];
$this->date = new \DateTime();
}
public function render(): string
{
return "Title: {$this->title}\n"
. "Body: {$this->body}\n"
. "Author: {$this->author->name} Date: {$this->date->format('Y-m-d')}\n"
. "Comments: " . implode(', ', $this->comments) . "\n";
}
public function __toString()
{
return $this->title;
}
}
class Author
{
public $name;
/** @var Page[] */
private $pages = [];
public function __construct($name)
{
$this->name = $name;
}
public function addToPage(Page $page)
{
$this->pages[] = $page;
}
public function getPages(): string
{
return 'Pages: ' . implode(', ', $this->pages);
}
}
# Client code example
// Example shows how to clone a complex Page object using the Prototype pattern
$author = new Author('John Doe');
$page = new Page('Article', 'Some text.', $author);
$page->addComment('1st comment');
echo $page->render();
/* Output:
Title: Article
Body: Some text.
Author: John Doe Date: 2018-10-01
Comments: 1st comment */
// Prototype pattern is available in PHP out of the box,
// we can use the `clone` keyword to create an exact copy of an object
$pageCopy = clone $page;
echo $pageCopy->render();
/* Output:
Title: Article(copy)
Body: Some text.
Author: John Doe Date: 2018-10-01
Comments: */
echo $author->getPages();
/* Output: Pages: Article, Article(copy) */