PSR-0 for Static Factory

This commit is contained in:
Trismegiste
2013-05-10 19:50:13 +02:00
parent 7ca8f615d7
commit 2bea1f390f
4 changed files with 34 additions and 20 deletions

View File

@@ -0,0 +1,8 @@
<?php
namespace DesignPatterns\StaticFactory;
class FormatNumber implements Formatter
{
}

View File

@@ -0,0 +1,8 @@
<?php
namespace DesignPatterns\StaticFactory;
class FormatString implements Formatter
{
}

View File

@@ -0,0 +1,8 @@
<?php
namespace DesignPatterns\StaticFactory;
interface Formatter
{
}

View File

@@ -1,9 +1,9 @@
<?php <?php
namespace DesignPatterns; namespace DesignPatterns\StaticFactory;
/** /**
* Factory Method pattern * Static Factory pattern
* *
* Purpose: * Purpose:
* similar to the AbstractFactory, this pattern is used to create series of related or dependant objects. * similar to the AbstractFactory, this pattern is used to create series of related or dependant objects.
@@ -13,9 +13,12 @@ namespace DesignPatterns;
* Examples: * Examples:
* - Zend Framework: Zend_Cache_Backend or _Frontend use a factory method create cache backends or frontends * - Zend Framework: Zend_Cache_Backend or _Frontend use a factory method create cache backends or frontends
* *
* Note1: Remember, static => global => evil
* Note2: Cannot be subclassed or mock-uped or have multiple different instances
*/ */
class FactoryMethod class StaticFactory
{ {
/** /**
* the parametrized function to get create an instance * the parametrized function to get create an instance
* *
@@ -24,26 +27,13 @@ class FactoryMethod
*/ */
public static function factory($type) public static function factory($type)
{ {
$className = 'Format' . ucfirst($type); $className = __NAMESPACE__ . '\Format' . ucfirst($type);
if ( ! class_exists($className)) {
throw new Exception('Missing format class.'); if (!class_exists($className)) {
throw new \InvalidArgumentException('Missing format class.');
} }
return new $className(); return new $className();
} }
}
interface Formatter
{
} }
class FormatString implements Formatter
{
}
class FormatNumber implements Formatter
{
}