Client.php 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. <?php
  2. namespace Predis;
  3. use Predis\Network\IConnection;
  4. use Predis\Network\IConnectionSingle;
  5. use Predis\Network\ConnectionCluster;
  6. use Predis\Profiles\ServerProfile;
  7. use Predis\Profiles\IServerProfile;
  8. class Client {
  9. private static $_connectionSchemes;
  10. private $_options, $_profile, $_connection;
  11. public function __construct($parameters = null, $options = null) {
  12. $this->_options = $this->filterOptions($options ?: new ClientOptions());
  13. $this->_profile = $this->_options->profile;
  14. $this->_connection = $this->initializeConnection($parameters);
  15. }
  16. private function filterOptions($options) {
  17. if ($options instanceof ClientOptions) {
  18. return $options;
  19. }
  20. if (is_array($options)) {
  21. return new ClientOptions($options);
  22. }
  23. if ($options instanceof IServerProfile) {
  24. return new ClientOptions(array('profile' => $options));
  25. }
  26. if (is_string($options)) {
  27. $profile = ServerProfile::get($options);
  28. return new ClientOptions(array('profile' => $profile));
  29. }
  30. throw new \InvalidArgumentException("Invalid type for client options");
  31. }
  32. private function initializeConnection($parameters = array()) {
  33. if (!isset($parameters)) {
  34. return $this->createConnection(array());
  35. }
  36. if ($parameters instanceof IConnection) {
  37. return $parameters;
  38. }
  39. if (is_array($parameters) && isset($parameters[0])) {
  40. $cluster = new ConnectionCluster($this->_options->key_distribution);
  41. foreach ($parameters as $single) {
  42. $cluster->add($single instanceof IConnectionSingle
  43. ? $single : $this->createConnection($single)
  44. );
  45. }
  46. return $cluster;
  47. }
  48. return $this->createConnection($parameters);
  49. }
  50. private function createConnection($parameters) {
  51. if (is_array($parameters) || is_string($parameters)) {
  52. $parameters = new ConnectionParameters($parameters);
  53. }
  54. else if (!$parameters instanceof ConnectionParameters) {
  55. $type = is_object($parameters) ? get_class($parameters) : gettype($parameters);
  56. throw new \InvalidArgumentException(
  57. "Cannot create a connection using an argument of type $type"
  58. );
  59. }
  60. $options = $this->_options;
  61. $connection = self::newConnection($parameters);
  62. $protocol = $connection->getProtocol();
  63. $protocol->setOption('iterable_multibulk', $options->iterable_multibulk);
  64. $protocol->setOption('throw_errors', $options->throw_errors);
  65. $this->pushInitCommands($connection);
  66. $callback = $this->_options->on_connection_initialized;
  67. if (isset($callback)) {
  68. $callback($this, $connection);
  69. }
  70. return $connection;
  71. }
  72. private function pushInitCommands(IConnectionSingle $connection) {
  73. $params = $connection->getParameters();
  74. if (isset($params->password)) {
  75. $connection->pushInitCommand($this->createCommand(
  76. 'auth', array($params->password)
  77. ));
  78. }
  79. if (isset($params->database)) {
  80. $connection->pushInitCommand($this->createCommand(
  81. 'select', array($params->database)
  82. ));
  83. }
  84. }
  85. public function getProfile() {
  86. return $this->_profile;
  87. }
  88. public function getOptions() {
  89. return $this->_options;
  90. }
  91. public function getClientFor($connectionAlias) {
  92. if (!Utils::isCluster($this->_connection)) {
  93. throw new ClientException(
  94. 'This method is supported only when the client is connected to a cluster of connections'
  95. );
  96. }
  97. $connection = $this->_connection->getConnectionById($connectionAlias);
  98. if ($connection === null) {
  99. throw new \InvalidArgumentException(
  100. "Invalid connection alias: '$connectionAlias'"
  101. );
  102. }
  103. return new Client($connection, $this->_options);
  104. }
  105. public function connect() {
  106. if (!$this->_connection->isConnected()) {
  107. $this->_connection->connect();
  108. }
  109. }
  110. public function disconnect() {
  111. $this->_connection->disconnect();
  112. }
  113. public function isConnected() {
  114. return $this->_connection->isConnected();
  115. }
  116. public function getConnection($id = null) {
  117. $connection = $this->_connection;
  118. if (!isset($id)) {
  119. return $connection;
  120. }
  121. $isCluster = Utils::isCluster($connection);
  122. return $isCluster ? $connection->getConnectionById($id) : $connection;
  123. }
  124. public function __call($method, $arguments) {
  125. $command = $this->_profile->createCommand($method, $arguments);
  126. return $this->_connection->executeCommand($command);
  127. }
  128. public function createCommand($method, $arguments = array()) {
  129. return $this->_profile->createCommand($method, $arguments);
  130. }
  131. public function executeCommand(ICommand $command) {
  132. return $this->_connection->executeCommand($command);
  133. }
  134. public function executeCommandOnShards(ICommand $command) {
  135. if (Utils::isCluster($this->_connection)) {
  136. $replies = array();
  137. foreach ($this->_connection as $connection) {
  138. $replies[] = $connection->executeCommand($command);
  139. }
  140. return $replies;
  141. }
  142. return array($this->_connection->executeCommand($command));
  143. }
  144. private function sharedInitializer($argv, $initializer) {
  145. $argc = count($argv);
  146. if ($argc === 0) {
  147. return $this->$initializer();
  148. }
  149. else if ($argc === 1) {
  150. list($arg0) = $argv;
  151. return is_array($arg0) ? $this->$initializer($arg0) : $this->$initializer(null, $arg0);
  152. }
  153. else if ($argc === 2) {
  154. list($arg0, $arg1) = $argv;
  155. return $this->$initializer($arg0, $arg1);
  156. }
  157. return $this->$initializer($this, $arguments);
  158. }
  159. public function pipeline(/* arguments */) {
  160. return $this->sharedInitializer(func_get_args(), 'initPipeline');
  161. }
  162. private function initPipeline(Array $options = null, $pipelineBlock = null) {
  163. $pipeline = null;
  164. if (isset($options)) {
  165. if (isset($options['safe']) && $options['safe'] == true) {
  166. $connection = $this->_connection;
  167. $pipeline = new CommandPipeline($this,
  168. Utils::isCluster($connection)
  169. ? new Pipeline\SafeClusterExecutor($connection)
  170. : new Pipeline\SafeExecutor($connection)
  171. );
  172. }
  173. else {
  174. $pipeline = new CommandPipeline($this);
  175. }
  176. }
  177. return $this->pipelineExecute(
  178. $pipeline ?: new CommandPipeline($this), $pipelineBlock
  179. );
  180. }
  181. private function pipelineExecute(CommandPipeline $pipeline, $block) {
  182. return $block !== null ? $pipeline->execute($block) : $pipeline;
  183. }
  184. public function multiExec(/* arguments */) {
  185. return $this->sharedInitializer(func_get_args(), 'initMultiExec');
  186. }
  187. private function initMultiExec(Array $options = null, $transBlock = null) {
  188. $multi = isset($options) ? new MultiExecContext($this, $options) : new MultiExecContext($this);
  189. return $transBlock !== null ? $multi->execute($transBlock) : $multi;
  190. }
  191. public function pubSubContext(Array $options = null) {
  192. return new PubSubContext($this, $options);
  193. }
  194. private static function ensureDefaultSchemes() {
  195. if (!isset(self::$_connectionSchemes)) {
  196. self::$_connectionSchemes = array(
  197. 'tcp' => '\Predis\Network\TcpConnection',
  198. 'unix' => '\Predis\Network\UnixDomainSocketConnection',
  199. // Compatibility with older versions.
  200. 'redis' => '\Predis\Network\TcpConnection',
  201. );
  202. }
  203. }
  204. public static function registerScheme($scheme, $connectionClass) {
  205. self::ensureDefaultSchemes();
  206. $connectionReflection = new \ReflectionClass($connectionClass);
  207. if (!$connectionReflection->isSubclassOf('\Predis\Network\IConnectionSingle')) {
  208. throw new ClientException(
  209. "Cannot register '$connectionClass' as it is not a valid connection class"
  210. );
  211. }
  212. self::$_connectionSchemes[$scheme] = $connectionClass;
  213. }
  214. public static function getConnectionClass($scheme) {
  215. self::ensureDefaultSchemes();
  216. if (!isset(self::$_connectionSchemes[$scheme])) {
  217. throw new ClientException("Unknown connection scheme: $scheme");
  218. }
  219. return self::$_connectionSchemes[$scheme];
  220. }
  221. private static function newConnection(ConnectionParameters $parameters, IRedisProtocol $protocol = null) {
  222. $connection = self::getConnectionClass($parameters->scheme);
  223. return new $connection($parameters, $protocol);
  224. }
  225. public static function newConnectionByScheme($scheme, $parameters = array()) {
  226. $connection = self::getConnectionClass($scheme);
  227. if (!$parameters instanceof ConnectionParameters) {
  228. $parameters = new ConnectionParameters($parameters);
  229. }
  230. return self::newConnection($parameters);
  231. }
  232. }