Skip to content

Instantly share code, notes, and snippets.

@MaximStrutinskiy
Created September 20, 2017 14:53
Show Gist options
  • Save MaximStrutinskiy/c02db67ce550efccefd5333d8a8d59b3 to your computer and use it in GitHub Desktop.
Save MaximStrutinskiy/c02db67ce550efccefd5333d8a8d59b3 to your computer and use it in GitHub Desktop.
<?php
namespace DesignPatterns\Creational\AbstractFactory;
/**
* In this case, the abstract factory is a contract for creating some components
* for the web. There are two ways of rendering text: HTML and JSON
*/
abstract class AbstractFactory
{
abstract public function createText(string $content): Text;
}
<?php
namespace DesignPatterns\Creational\AbstractFactory\Tests;
use DesignPatterns\Creational\AbstractFactory\HtmlFactory;
use DesignPatterns\Creational\AbstractFactory\HtmlText;
use DesignPatterns\Creational\AbstractFactory\JsonFactory;
use DesignPatterns\Creational\AbstractFactory\JsonText;
use PHPUnit\Framework\TestCase;
class AbstractFactoryTest extends TestCase
{
public function testCanCreateHtmlText()
{
$factory = new HtmlFactory();
$text = $factory->createText('foobar');
$this->assertInstanceOf(HtmlText::class, $text);
}
public function testCanCreateJsonText()
{
$factory = new JsonFactory();
$text = $factory->createText('foobar');
$this->assertInstanceOf(JsonText::class, $text);
}
}
<?php
namespace DesignPatterns\Creational\AbstractFactory;
class HtmlFactory extends AbstractFactory
{
public function createText(string $content): Text
{
return new HtmlText($content);
}
}
<?php
namespace DesignPatterns\Creational\AbstractFactory;
class HtmlText extends Text
{
// do something here
}
<?php
namespace DesignPatterns\Creational\AbstractFactory;
class JsonFactory extends AbstractFactory
{
public function createText(string $content): Text
{
return new JsonText($content);
}
}
<?php
namespace DesignPatterns\Creational\AbstractFactory;
class JsonText extends Text
{
// do something here
}
<?php
namespace DesignPatterns\Creational\AbstractFactory;
abstract class Text
{
/**
* @var string
*/
private $text;
public function __construct(string $text)
{
$this->text = $text;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment