Skip to content

Commit e675a5f

Browse files
author
Dominik Liebler
committed
PHP7 Static Factory
1 parent ce1b538 commit e675a5f

File tree

2 files changed

+20
-28
lines changed

2 files changed

+20
-28
lines changed

Creational/StaticFactory/StaticFactory.php

+9-13
Original file line numberDiff line numberDiff line change
@@ -3,30 +3,26 @@
33
namespace DesignPatterns\Creational\StaticFactory;
44

55
/**
6-
* Note1: Remember, static => global => evil
6+
* Note1: Remember, static means global state which is evil because it can't be mocked for tests
77
* Note2: Cannot be subclassed or mock-upped or have multiple different instances.
88
*/
9-
class StaticFactory
9+
final class StaticFactory
1010
{
1111
/**
12-
* the parametrized function to get create an instance.
13-
*
1412
* @param string $type
1513
*
16-
* @static
17-
*
18-
* @throws \InvalidArgumentException
19-
*
2014
* @return FormatterInterface
2115
*/
22-
public static function factory($type)
16+
public static function factory(string $type): FormatterInterface
2317
{
24-
$className = __NAMESPACE__.'\Format'.ucfirst($type);
18+
if ($type == 'number') {
19+
return new FormatNumber();
20+
}
2521

26-
if (!class_exists($className)) {
27-
throw new \InvalidArgumentException('Missing format class.');
22+
if ($type == 'string') {
23+
return new FormatString();
2824
}
2925

30-
return new $className();
26+
throw new \InvalidArgumentException('Unknown format given');
3127
}
3228
}

Creational/StaticFactory/Tests/StaticFactoryTest.php

+11-15
Original file line numberDiff line numberDiff line change
@@ -4,33 +4,29 @@
44

55
use DesignPatterns\Creational\StaticFactory\StaticFactory;
66

7-
/**
8-
* Tests for Static Factory pattern.
9-
*/
107
class StaticFactoryTest extends \PHPUnit_Framework_TestCase
118
{
12-
public function getTypeList()
9+
public function testCanCreateNumberFormatter()
1310
{
14-
return array(
15-
array('string'),
16-
array('number'),
11+
$this->assertInstanceOf(
12+
'DesignPatterns\Creational\StaticFactory\FormatNumber',
13+
StaticFactory::factory('number')
1714
);
1815
}
1916

20-
/**
21-
* @dataProvider getTypeList
22-
*/
23-
public function testCreation($type)
17+
public function testCanCreateStringFormatter()
2418
{
25-
$obj = StaticFactory::factory($type);
26-
$this->assertInstanceOf('DesignPatterns\Creational\StaticFactory\FormatterInterface', $obj);
19+
$this->assertInstanceOf(
20+
'DesignPatterns\Creational\StaticFactory\FormatString',
21+
StaticFactory::factory('string')
22+
);
2723
}
2824

2925
/**
30-
* @expectedException InvalidArgumentException
26+
* @expectedException \InvalidArgumentException
3127
*/
3228
public function testException()
3329
{
34-
StaticFactory::factory('');
30+
StaticFactory::factory('object');
3531
}
3632
}

0 commit comments

Comments
 (0)