Skip to content

Instantly share code, notes, and snippets.

@pierredup
Created May 24, 2014 20:10
Show Gist options
  • Save pierredup/5bbf01340aeb7ff43948 to your computer and use it in GitHub Desktop.
Save pierredup/5bbf01340aeb7ff43948 to your computer and use it in GitHub Desktop.
<?php
class AdapterFactory
{
private $adapters = [];
public function registerAdapter($name, callback $adapterFactory, callback $adapterConfigurator
{
$this->adapter[$adapter] = [$adapterFactory, $adapterConfigurator];
}
public function createAdapter($adapter, array $config)
{
return $this->adapter[$adapter][0]($config);
}
public function createAdapterConfiguration($adapter, Output $output, DialogHelper $dialogHelper, )
{
return $this->adapter[$adapter][1]($output, $dialogHelper);
}
}
class Application
{
//AdapterFactory
private $factory = null;
// configured/availible adapters (aka config-slots)
private $adapters = [];
private $currentAdapter = null;
/*
$adapters = [
'my_adapter' => [
'adapter_name' => 'github',
'instance' => {GitHubAdapter object} or null
'config' => [...]
]
];
*/
public function setCurrentAdapter($adapter)
{
$this->currentAdapter = $adapter;
}
public function setAdapter($name, $adapter, array $config)
{
$this->adapters[$name] = [
'adapter_name' => 'github',
'instance' => null,
'config' => $config,
];
}
public function getAdapter($name=null)
{
$name = $name :? $this->currentAdapter;
if (null === $this->adapters[$name]['instance']) {
$this->adapters[$name]['instance'] = $this->factory->createAdapter(
$this->adapters[$name]['adapter_name'],
$this->adapters[$name]['config'],
);
}
return $this->adapters[$name]['instance'];
}
}
$factory = new AdapterFactory();
$factory->registerAdapter(
'github',
function ($config) { return new GitHubAdapter($config); },
function ($config) { return new DefaultConfigurator($output, $dialogHelper, 'GitHub', url='https://api.github.com/', supportTokens=true); }
);
$config = new Config();
$application = new Application($factory, $config);
foreach ($config->get('adapters') as $slotName => $slot) {
$application->setAdapter($slotName, $slot['adapter_name'], $slot['config']);
}
$application->setCurrentAdapter($config->get('default_adapter'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment