这是一个成熟的工厂对象,它演示了自动加载、命名空间支持、来自非静态实例(具有可变路径)的可调用对象、加载错误和自定义异常的处理。
abstract class AbstractFactory implements \ArrayAccess
{
protected $manifest;
function __construct($manifest)
{
$this->manifest = $manifest;
}
abstract function produce($name);
public function offsetExists($offset)
{
return isset($this->manifest[$offset]);
}
public function offsetGet($offset)
{
return $this->produce($offset);
}
//implement stubs for other ArrayAccess funcs
}
abstract class SimpleFactory extends AbstractFactory {
protected $description;
protected $path;
protected $namespace;
function __construct($manifest, $path, $namespace = "jj\\") {
parent::__construct($manifest);
$this->path = $path;
$this->namespace = $namespace;
if (! spl_autoload_register(array($this, 'autoload'), false)) //throws exceptions on its own, but we want a custom one
throw new \RuntimeException(get_class($this)." failed to register autoload.");
}
function __destruct()
{
spl_autoload_unregister(array($this, 'autoload'));
}
public function autoload($class_name) {
$file = str_replace($this->namespace, '', $class_name);
$filename = $this->path.$file.'.php';
if (file_exists($filename))
try {
require $filename; //TODO add global set_error_handler and try clause to catch parse errors
} catch (Exception $e) {} //autoload exceptions are not passed by design, nothing to do
}
function produce($name) {
if (isset($this->manifest[$name])) {
$class = $this->namespace.$this->manifest[$name];
if (class_exists($class, $autoload = true)) {
return new $class();
} else throw new \jj\SystemConfigurationException('Factory '.get_class($this)." was unable to produce a new class {$class}", 'SYSTEM_ERROR', $this);
//an example of a custom exception with a string code and data container
} else throw new LogicException("Unknown {$this->description} {$name}.");
}
function __toString() //description function if custom exception class wants a string explanation for its container
{
return $this->description." factory ".get_class($this)."(path={$this->path}, namespace={$this->namespace}, map: ".json_encode($this->manifest).")";
}
}
最后是一个例子:
namespace jj;
require_once('lib/AbstractFactory.php');
require_once('lib/CurrenciesProvider.php'); //base abstract class for all banking objects that are created
class CurrencyProviders extends SimpleFactory
{
function __construct()
{
$manifest = array(
'Germany' => 'GermanBankCurrencies',
'Switzerland' => 'SwissBankCurrencies'
);
parent::__construct($manifest, __DIR__.'/CurrencyProviders/', //you have total control over relative or absolute paths here
'banks\');
$this->description = 'currency provider country name';
}
}
现在做
$currencies_cache = (new \jj\CurrencyProviders())['Germany'];
或者
$currencies_cache = (new \jj\CurrencyProviders())['Ukraine'];
LogicException("未知货币提供者国家名称乌克兰")
如果 /CurrencyProviders/ 中没有 SwissCurrencies.php 文件,
\jj\SystemConfigurationException('工厂 jj\CurrencyProviders 无法生成新类银行\SwissCurrencies。调试数据:货币提供者国家名称工厂 jj\CurrencyProviders(path=/var/www/hosted/site/.../CurrencyProviders/ , 命名空间=银行\, 地图: {"Germany": "GermanBankCurrencies", "Switzerland":"SwissBankCurrencies"}')
通过足够的努力,可以扩展这个工厂来捕获解析错误(如何在 PHP 中捕获 require() 或 include() 的错误?)并将参数传递给构造函数。