I have no idea if this pattern has a name
In my humble opinion, the connection pool would actually make sense. Only you should not initialize all the connections right off. Instead use lazy initialization:
class LazyPool
{
private $connections = [];
private $providers = [];
public function addProvider($name, callable $provider)
{
$this->providers[$name] = $provider;
return $this;
}
public function getConnection($name)
{
if (array_key_exists($name, $this->connections) === false)
{
$this->connections[$name] = call_user_func($this->providers[$name]);
}
return $this->connections[$name];
}
}
This class can would be used like this:
$pool = new LazyPool;
$pool->addProvider('lorem', function() use ($config){
$instance = new SoapThing($config['wsdl_1']);
return $instance;
});
$pool->addProvider('ipsum', function() use ($config){
$instance = new SoapThing($config['i_think_it_was_wsdl']);
return $instance;
});
$foo = new Foo($pool);
$bar = new Bar($pool);
This way both instance will be able to initialize SOAP connection, but if Foo
initialized connection named "ipsum"
, then Bar
instance will get from pool the already initialized SOAP client.
Disclaimer:
This code was not tested. It was written directly in the SO post editor using some copy-paste from older post of mine. This particular syntax also will require PHP 5.4+, therefore you might need to adapt it for running in older PHP 5.* versions.