1.1. Abstract Factory

1.1.1. Purpose

To create series of related or dependent objects without specifyingtheir concrete classes. Usually the created classes all implement thesame interface. The client of the abstract factory does not care abouthow these objects are created, he just knows how they go together.

1.1.2. UML Diagram

Alt AbstractFactory UML Diagram

1.1.3. Code

You can also find this code on GitHub

Parser.php

  1. <?php
  2.  
  3. namespace DesignPatterns\Creational\AbstractFactory;
  4.  
  5. interface Parser
  6. {
  7. public function parse(string $input): array;
  8. }

CsvParser.php

  1. <?php
  2.  
  3. namespace DesignPatterns\Creational\AbstractFactory;
  4.  
  5. class CsvParser implements Parser
  6. {
  7. const OPTION_CONTAINS_HEADER = true;
  8. const OPTION_CONTAINS_NO_HEADER = false;
  9.  
  10. /**
  11. * @var bool
  12. */
  13. private $skipHeaderLine;
  14.  
  15. public function __construct(bool $skipHeaderLine)
  16. {
  17. $this->skipHeaderLine = $skipHeaderLine;
  18. }
  19.  
  20. public function parse(string $input): array
  21. {
  22. $headerWasParsed = false;
  23. $parsedLines = [];
  24.  
  25. foreach (explode(PHP_EOL, $input) as $line) {
  26. if (!$headerWasParsed && $this->skipHeaderLine === self::OPTION_CONTAINS_HEADER) {
  27. continue;
  28. }
  29.  
  30. $parsedLines[] = str_getcsv($line);
  31. }
  32.  
  33. return $parsedLines;
  34. }
  35. }

JsonParser.php

  1. <?php
  2.  
  3. namespace DesignPatterns\Creational\AbstractFactory;
  4.  
  5. class JsonParser implements Parser
  6. {
  7. public function parse(string $input): array
  8. {
  9. return json_decode($input, true);
  10. }
  11. }

ParserFactory.php

  1. <?php
  2.  
  3. namespace DesignPatterns\Creational\AbstractFactory;
  4.  
  5. class ParserFactory
  6. {
  7. public function createCsvParser(bool $skipHeaderLine): CsvParser
  8. {
  9. return new CsvParser($skipHeaderLine);
  10. }
  11.  
  12. public function createJsonParser(): JsonParser
  13. {
  14. return new JsonParser();
  15. }
  16. }

1.1.4. Test

Tests/AbstractFactoryTest.php

  1. <?php
  2.  
  3. namespace DesignPatterns\Creational\AbstractFactory\Tests;
  4.  
  5. use DesignPatterns\Creational\AbstractFactory\CsvParser;
  6. use DesignPatterns\Creational\AbstractFactory\JsonParser;
  7. use DesignPatterns\Creational\AbstractFactory\ParserFactory;
  8. use PHPUnit\Framework\TestCase;
  9.  
  10. class AbstractFactoryTest extends TestCase
  11. {
  12. public function testCanCreateCsvParser()
  13. {
  14. $factory = new ParserFactory();
  15. $parser = $factory->createCsvParser(CsvParser::OPTION_CONTAINS_HEADER);
  16.  
  17. $this->assertInstanceOf(CsvParser::class, $parser);
  18. }
  19.  
  20. public function testCanCreateJsonParser()
  21. {
  22. $factory = new ParserFactory();
  23. $parser = $factory->createJsonParser();
  24.  
  25. $this->assertInstanceOf(JsonParser::class, $parser);
  26. }
  27. }