From 2543bb30cc91c6f49c5bccd7ff3e09079b5cc751 Mon Sep 17 00:00:00 2001 From: Daniele Alessandri Date: Thu, 10 Jun 2010 19:47:40 +0200 Subject: [PATCH] Map URI schemes to connection classes. --- lib/Predis.php | 43 +++++++++++++++++++++++++++++++++++++------ 1 file changed, 37 insertions(+), 6 deletions(-) diff --git a/lib/Predis.php b/lib/Predis.php index 6ee1ca72..3cf1bfa6 100644 --- a/lib/Predis.php +++ b/lib/Predis.php @@ -113,7 +113,7 @@ class Client { private function createConnection($parameters) { $params = new ConnectionParameters($parameters); - $connection = $this->createConnectionInstance($params); + $connection = Connection::create($params, $this->_responseReader); if ($params->password !== null) { $connection->pushInitCommand($this->createCommand( @@ -129,11 +129,6 @@ class Client { return $connection; } - private function createConnectionInstance(ConnectionParameters $parameters) { - // TODO: check scheme and return the appropriate IConnectionSingle instance - return new TcpConnection($parameters, $this->_responseReader); - } - private function setConnection(IConnection $connection) { $this->_connection = $connection; } @@ -1102,6 +1097,42 @@ interface IConnectionCluster extends IConnection { public function getConnectionById($connectionId); } +class Connection { + private static $_registeredSchemes; + + private static function ensureInitialized() { + if (!isset(self::$_registeredSchemes)) { + self::$_registeredSchemes = self::getDefaultSchemes(); + } + } + + private static function getDefaultSchemes() { + return array( + 'tcp' => '\Predis\TcpConnection', + ); + } + + public static function registerScheme($scheme, $connectionClass) { + self::ensureInitialized(); + $connectionReflection = new \ReflectionClass($connectionClass); + if (!$connectionReflection->isSubclassOf('\Predis\IConnectionSingle')) { + throw new ClientException( + "Cannot register '$connectionClass' as it is not a valid connection class" + ); + } + self::$_registeredSchemes[$scheme] = $connectionClass; + } + + public static function create(ConnectionParameters $parameters, ResponseReader $reader) { + self::ensureInitialized(); + if (!isset(self::$_registeredSchemes[$parameters->scheme])) { + throw new ClientException("Unknown connection scheme: {$parameters->scheme}"); + } + $connection = self::$_registeredSchemes[$parameters->scheme]; + return new $connection($parameters, $reader); + } +} + class TcpConnection implements IConnectionSingle { private $_params, $_socket, $_initCmds, $_reader;