diff --git a/SimpleFactory/Bicycle.php b/SimpleFactory/Bicycle.php new file mode 100644 index 0000000..39c2d32 --- /dev/null +++ b/SimpleFactory/Bicycle.php @@ -0,0 +1,20 @@ + global => evil + * + * Therefore, you can haZ multiple factories, differently parametrized, + * you can subclass it and you can mock-up it. + */ +class ConcreteFactory +{ + + protected $typeList; + + /** + * You can imagine to inject your own type list or merge with + * the default ones... + */ + public function __construct() + { + $this->typeList = array( + 'bicycle' => __NAMESPACE__ . '\Bicycle', + 'other' => __NAMESPACE__ . '\Scooter' + ); + } + + /** + * Creates a vehicle + * + * @param string $type a known type key + * @return Vehicle a new instance of Vehicle + * @throws \InvalidArgumentException + */ + public function createVehicle($type) + { + if (!array_key_exists($type, $this->typeList)) { + throw new \InvalidArgumentException("$type is not valid vehicle"); + } + $className = $this->typeList[$type]; + + return new $className(); + } + +} \ No newline at end of file diff --git a/SimpleFactory/Scooter.php b/SimpleFactory/Scooter.php new file mode 100644 index 0000000..925d7d2 --- /dev/null +++ b/SimpleFactory/Scooter.php @@ -0,0 +1,20 @@ +factory = new ConcreteFactory(); + } + + public function getType() + { + return array( + array('bicycle'), + array('other') + ); + } + + /** + * @dataProvider getType + */ + public function testCreation($type) + { + $obj = $this->factory->createVehicle($type); + $this->assertInstanceOf('DesignPatterns\SimpleFactory\Vehicle', $obj); + } + + /** + * @expectedException \InvalidArgumentException + */ + public function testBadType() + { + $this->factory->createVehicle('car'); + } + +} \ No newline at end of file