diff --git a/CHANGELOG.md b/CHANGELOG.md index 892d5f0f..7cc045ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,10 @@ v0.8.3 (2013-xx-xx) hash slots instead of 4096 to reflect this recent change from redis unstable ([see this commit](https://github.com/antirez/redis/commit/ebd666d)). +- The constructor of `Predis\Client` now accepts a callable as first argument + returning `Predis\Connection\ConnectionInterface`. Users can create their + own self-contained strategies to create and set up the underlying connection. + v0.8.2 (2013-02-03) =============================================================================== diff --git a/lib/Predis/Client.php b/lib/Predis/Client.php index 4bdb15a1..36482c60 100644 --- a/lib/Predis/Client.php +++ b/lib/Predis/Client.php @@ -100,6 +100,18 @@ class Client implements ClientInterface return $this->connections->createAggregated($connection, $parameters); } + if (is_callable($parameters)) { + $connection = call_user_func($parameters, $this->options); + + if (!$connection instanceof ConnectionInterface) { + throw new \InvalidArgumentException( + 'Callable parameters must return instances of Predis\Connection\ConnectionInterface' + ); + } + + return $connection; + } + return $this->connections->create($parameters); } diff --git a/tests/Predis/ClientTest.php b/tests/Predis/ClientTest.php index b8db3848..5d3f16be 100644 --- a/tests/Predis/ClientTest.php +++ b/tests/Predis/ClientTest.php @@ -197,6 +197,42 @@ class ClientTest extends StandardTestCase $this->assertSame($replication, $client->getConnection()); } + /** + * @group disconnected + */ + public function testConstructorWithCallableArgument() + { + $connection = $this->getMock('Predis\Connection\ConnectionInterface'); + + $callable = $this->getMock('stdClass', array('__invoke')); + $callable->expects($this->once()) + ->method('__invoke') + ->with($this->isInstanceOf('Predis\Option\ClientOptions')) + ->will($this->returnValue($connection)); + + $client = new Client($callable); + + $this->assertSame($connection, $client->getConnection()); + } + + /** + * @group disconnected + * @expectedException InvalidArgumentException + * @expectedExceptionMessage Callable parameters must return instances of Predis\Connection\ConnectionInterface + */ + public function testConstructorWithCallableArgumentButInvalidReturnType() + { + $wrongType = $this->getMock('stdClass'); + + $callable = $this->getMock('stdClass', array('__invoke')); + $callable->expects($this->once()) + ->method('__invoke') + ->with($this->isInstanceOf('Predis\Option\ClientOptions')) + ->will($this->returnValue($wrongType)); + + $client = new Client($callable); + } + /** * @group disconnected */