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
1.1.3. Code
You can also find this code on GitHub
Parser.php
- <?php
- namespace DesignPatterns\Creational\AbstractFactory;
- interface Parser
- {
- public function parse(string $input): array;
- }
CsvParser.php
- <?php
- namespace DesignPatterns\Creational\AbstractFactory;
- class CsvParser implements Parser
- {
- const OPTION_CONTAINS_HEADER = true;
- const OPTION_CONTAINS_NO_HEADER = false;
- /**
- * @var bool
- */
- private $skipHeaderLine;
- public function __construct(bool $skipHeaderLine)
- {
- $this->skipHeaderLine = $skipHeaderLine;
- }
- public function parse(string $input): array
- {
- $headerWasParsed = false;
- $parsedLines = [];
- foreach (explode(PHP_EOL, $input) as $line) {
- if (!$headerWasParsed && $this->skipHeaderLine === self::OPTION_CONTAINS_HEADER) {
- continue;
- }
- $parsedLines[] = str_getcsv($line);
- }
- return $parsedLines;
- }
- }
JsonParser.php
- <?php
- namespace DesignPatterns\Creational\AbstractFactory;
- class JsonParser implements Parser
- {
- public function parse(string $input): array
- {
- return json_decode($input, true);
- }
- }
ParserFactory.php
- <?php
- namespace DesignPatterns\Creational\AbstractFactory;
- class ParserFactory
- {
- public function createCsvParser(bool $skipHeaderLine): CsvParser
- {
- return new CsvParser($skipHeaderLine);
- }
- public function createJsonParser(): JsonParser
- {
- return new JsonParser();
- }
- }
1.1.4. Test
Tests/AbstractFactoryTest.php
- <?php
- namespace DesignPatterns\Creational\AbstractFactory\Tests;
- use DesignPatterns\Creational\AbstractFactory\CsvParser;
- use DesignPatterns\Creational\AbstractFactory\JsonParser;
- use DesignPatterns\Creational\AbstractFactory\ParserFactory;
- use PHPUnit\Framework\TestCase;
- class AbstractFactoryTest extends TestCase
- {
- public function testCanCreateCsvParser()
- {
- $factory = new ParserFactory();
- $parser = $factory->createCsvParser(CsvParser::OPTION_CONTAINS_HEADER);
- $this->assertInstanceOf(CsvParser::class, $parser);
- }
- public function testCanCreateJsonParser()
- {
- $factory = new ParserFactory();
- $parser = $factory->createJsonParser();
- $this->assertInstanceOf(JsonParser::class, $parser);
- }
- }