Addded Prototype Desin Pattern
This commit is contained in:
27
src/Pattern/Creational/Prototype/Author.php
Normal file
27
src/Pattern/Creational/Prototype/Author.php
Normal file
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @package: patterns
|
||||
* @author: Yevhen Odynets
|
||||
* @date: 2025-07-04
|
||||
* @time: 07:54
|
||||
*/
|
||||
|
||||
declare(strict_types = 1);
|
||||
|
||||
namespace Pattern\Creational\Prototype;
|
||||
|
||||
class Author
|
||||
{
|
||||
/**
|
||||
* @var Page[]
|
||||
*/
|
||||
private array $pages = [];
|
||||
|
||||
public function __construct(private string $name) {}
|
||||
|
||||
public function addToPage(Page $page): void
|
||||
{
|
||||
$this->pages[] = $page;
|
||||
}
|
||||
}
|
||||
60
src/Pattern/Creational/Prototype/Page.php
Normal file
60
src/Pattern/Creational/Prototype/Page.php
Normal file
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @package: patterns
|
||||
* @author: Yevhen Odynets
|
||||
* @date: 2025-07-04
|
||||
* @time: 07:53
|
||||
*/
|
||||
|
||||
declare(strict_types = 1);
|
||||
|
||||
namespace Pattern\Creational\Prototype;
|
||||
|
||||
use DateTime;
|
||||
|
||||
/**
|
||||
* Prototype.
|
||||
*/
|
||||
class Page
|
||||
{
|
||||
/** @noinspection PhpPropertyOnlyWrittenInspection */
|
||||
private array $comments = [];
|
||||
|
||||
/** @noinspection PhpPropertyOnlyWrittenInspection */
|
||||
private DateTime $date;
|
||||
|
||||
public function __construct(
|
||||
private string $title,
|
||||
private string $body,
|
||||
private readonly Author $author,
|
||||
) {
|
||||
$this->author->addToPage($this);
|
||||
$this->date = new DateTime();
|
||||
}
|
||||
|
||||
public function addComment(string $comment): void
|
||||
{
|
||||
$this->comments[] = $comment;
|
||||
}
|
||||
|
||||
/**
|
||||
* You can control what data you want to carry over to the cloned object.
|
||||
*
|
||||
* For instance, when a page is cloned:
|
||||
* - It gets a new "Copy of ..." title.
|
||||
* - The author of the page remains the same. Therefore we leave the
|
||||
* reference to the existing object while adding the cloned page to the list
|
||||
* of the author's pages.
|
||||
* - We don't carry over the comments from the old page.
|
||||
* - We also attach a new date object to the page.
|
||||
*/
|
||||
public function __clone(): void
|
||||
{
|
||||
$this->title = "КОПІЯ: " . $this->title;
|
||||
$this->body = "КОПІЯ: " . $this->body;
|
||||
$this->author->addToPage($this);
|
||||
$this->comments = [];
|
||||
$this->date = new DateTime();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user