factory, , , ( ), .
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);
}
}
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))
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;
} catch (Exception $e) {}
}
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);
} 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');
class CurrencyProviders extends SimpleFactory
{
function __construct()
{
$manifest = array(
'Germany' => 'GermanBankCurrencies',
'Switzerland' => 'SwissBankCurrencies'
);
parent::__construct($manifest, __DIR__.'/CurrencyProviders/',
'banks\');
$this->description = 'currency provider country name';
}
}
do
$currencies_cache = (new \jj\CurrencyProviders())['Germany'];
$currencies_cache = (new \jj\CurrencyProviders())['Ukraine'];
LogicException ( " - " )
/CurrencyProviders/,
SwissCurrencies.php,
\ jj\SystemConfigurationException ('Factory jj\CurrencyProviders bank\SwissCurrencies. : factory jj\CurrencyProviders ( =/var/www/hosting/site/.../CurrencyProviders/, namespace = banks \, map: { "": "GermanBankCurrencies", "": "SwissBankCurrencies" } ')
factory ( require() include() PHP?) .