CyberJack

object creation using factories without if/else

Apr 13th, 2023 (edited)
1,008
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.96 KB | None | 0 0
  1. <?php
  2.  
  3. interface Product {}
  4.  
  5. class Book implements Product {
  6.     public function __construct(
  7.         public readonly string $title,
  8.         public readonly string $author,
  9.     ) {}
  10. }
  11.  
  12. class BookFactory {
  13.     public static function create(): Book {
  14.         return new Book(
  15.             $_POST['title'] ?? '',
  16.             $_POST['author'] ?? '',
  17.         );
  18.     }
  19. }
  20.  
  21. class DVD implements Product {}
  22. class DVDFactory {}
  23.  
  24. class Furniture implements Product {}
  25. class FurnitureFactory {}
  26.  
  27. class ProductFactory {
  28.     public static function create(string $type): Product {
  29.         $factory = $type . 'Factory';
  30.         return $factory::create();
  31.     }
  32. }
  33.  
  34. $_POST = [
  35.     'type' => 'Book',
  36.     'title' => 'My Book',
  37.     'author' => 'The Author',
  38. ];
  39.  
  40. $product = ProductFactory::create($_POST['type']);
  41. var_dump($product);
  42.  
  43. // object(Book)#1 (2) {
  44. //   ["title"]=>
  45. //   string(7) "My Book"
  46. //   ["author"]=>
  47. //   string(10) "The Author"
  48. // }
  49.  
Advertisement
Add Comment
Please, Sign In to add comment