1.6. Prototype

1.6.1. Purpose

To avoid the cost of creating objects the standard way (new Foo()) andinstead create a prototype and clone it.

1.6.2. Examples

  • Large amounts of data (e.g. create 1,000,000 rows in a database atonce via a ORM).

1.6.3. UML Diagram

Alt Prototype UML Diagram

1.6.4. Code

You can also find this code on GitHub

BookPrototype.php

  1. <?php
  2.  
  3. namespace DesignPatterns\Creational\Prototype;
  4.  
  5. abstract class BookPrototype
  6. {
  7. /**
  8. * @var string
  9. */
  10. protected $title;
  11.  
  12. /**
  13. * @var string
  14. */
  15. protected $category;
  16.  
  17. abstract public function __clone();
  18.  
  19. public function getTitle(): string
  20. {
  21. return $this->title;
  22. }
  23.  
  24. public function setTitle($title)
  25. {
  26. $this->title = $title;
  27. }
  28. }

BarBookPrototype.php

  1. <?php
  2.  
  3. namespace DesignPatterns\Creational\Prototype;
  4.  
  5. class BarBookPrototype extends BookPrototype
  6. {
  7. /**
  8. * @var string
  9. */
  10. protected $category = 'Bar';
  11.  
  12. public function __clone()
  13. {
  14. }
  15. }

FooBookPrototype.php

  1. <?php
  2.  
  3. namespace DesignPatterns\Creational\Prototype;
  4.  
  5. class FooBookPrototype extends BookPrototype
  6. {
  7. /**
  8. * @var string
  9. */
  10. protected $category = 'Foo';
  11.  
  12. public function __clone()
  13. {
  14. }
  15. }

1.6.5. Test

Tests/PrototypeTest.php

  1. <?php
  2.  
  3. namespace DesignPatterns\Creational\Prototype\Tests;
  4.  
  5. use DesignPatterns\Creational\Prototype\BarBookPrototype;
  6. use DesignPatterns\Creational\Prototype\FooBookPrototype;
  7. use PHPUnit\Framework\TestCase;
  8.  
  9. class PrototypeTest extends TestCase
  10. {
  11. public function testCanGetFooBook()
  12. {
  13. $fooPrototype = new FooBookPrototype();
  14. $barPrototype = new BarBookPrototype();
  15.  
  16. for ($i = 0; $i < 10; $i++) {
  17. $book = clone $fooPrototype;
  18. $book->setTitle('Foo Book No ' . $i);
  19. $this->assertInstanceOf(FooBookPrototype::class, $book);
  20. }
  21.  
  22. for ($i = 0; $i < 5; $i++) {
  23. $book = clone $barPrototype;
  24. $book->setTitle('Bar Book No ' . $i);
  25. $this->assertInstanceOf(BarBookPrototype::class, $book);
  26. }
  27. }
  28. }