Client.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. <?php
  2. /*
  3. * This file is part of the Predis package.
  4. *
  5. * (c) Daniele Alessandri <suppakilla@gmail.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Predis;
  11. use Predis\Command\CommandInterface;
  12. use Predis\Command\ScriptedCommand;
  13. use Predis\Connection\AggregatedConnectionInterface;
  14. use Predis\Connection\ConnectionInterface;
  15. use Predis\Connection\ConnectionFactoryInterface;
  16. use Predis\Monitor\MonitorContext;
  17. use Predis\Option\ClientOptions;
  18. use Predis\Option\ClientOptionsInterface;
  19. use Predis\Pipeline\PipelineContext;
  20. use Predis\PubSub\PubSubContext;
  21. use Predis\Transaction\MultiExecContext;
  22. /**
  23. * Main class that exposes the most high-level interface to interact with Redis.
  24. *
  25. * @author Daniele Alessandri <suppakilla@gmail.com>
  26. */
  27. class Client implements ClientInterface
  28. {
  29. const VERSION = '0.8.7';
  30. private $options;
  31. private $profile;
  32. private $connection;
  33. /**
  34. * Initializes a new client with optional connection parameters and client options.
  35. *
  36. * @param mixed $parameters Connection parameters for one or multiple servers.
  37. * @param mixed $options Options that specify certain behaviours for the client.
  38. */
  39. public function __construct($parameters = null, $options = null)
  40. {
  41. $this->options = $this->filterOptions($options);
  42. $this->profile = $this->options->profile;
  43. $this->connection = $this->initializeConnection($parameters);
  44. }
  45. /**
  46. * Creates an instance of Predis\Option\ClientOptions from various types of
  47. * arguments (string, array, Predis\Profile\ServerProfile) or returns the
  48. * passed object if it is an instance of Predis\Option\ClientOptions.
  49. *
  50. * @param mixed $options Client options.
  51. * @return ClientOptions
  52. */
  53. protected function filterOptions($options)
  54. {
  55. if (!isset($options)) {
  56. return new ClientOptions();
  57. }
  58. if (is_array($options)) {
  59. return new ClientOptions($options);
  60. }
  61. if ($options instanceof ClientOptionsInterface) {
  62. return $options;
  63. }
  64. throw new \InvalidArgumentException("Invalid type for client options");
  65. }
  66. /**
  67. * Initializes one or multiple connection (cluster) objects from various
  68. * types of arguments (string, array) or returns the passed object if it
  69. * implements Predis\Connection\ConnectionInterface.
  70. *
  71. * @param mixed $parameters Connection parameters or instance.
  72. * @return ConnectionInterface
  73. */
  74. protected function initializeConnection($parameters)
  75. {
  76. if ($parameters instanceof ConnectionInterface) {
  77. return $parameters;
  78. }
  79. if (is_array($parameters) && isset($parameters[0])) {
  80. $options = $this->options;
  81. $replication = isset($options->replication) && $options->replication;
  82. $connection = $options->{$replication ? 'replication' : 'cluster'};
  83. return $options->connections->createAggregated($connection, $parameters);
  84. }
  85. if (is_callable($parameters)) {
  86. $connection = call_user_func($parameters, $this->options);
  87. if (!$connection instanceof ConnectionInterface) {
  88. throw new \InvalidArgumentException(
  89. 'Callable parameters must return instances of Predis\Connection\ConnectionInterface'
  90. );
  91. }
  92. return $connection;
  93. }
  94. return $this->options->connections->create($parameters);
  95. }
  96. /**
  97. * {@inheritdoc}
  98. */
  99. public function getProfile()
  100. {
  101. return $this->profile;
  102. }
  103. /**
  104. * {@inheritdoc}
  105. */
  106. public function getOptions()
  107. {
  108. return $this->options;
  109. }
  110. /**
  111. * Returns the connection factory object used by the client.
  112. *
  113. * @return ConnectionFactoryInterface
  114. */
  115. public function getConnectionFactory()
  116. {
  117. return $this->options->connections;
  118. }
  119. /**
  120. * Returns a new instance of a client for the specified connection when the
  121. * client is connected to a cluster. The new instance will use the same
  122. * options of the original client.
  123. *
  124. * @param string $connectionID Identifier for the connection.
  125. * @return Client
  126. */
  127. public function getClientFor($connectionID)
  128. {
  129. if (!$connection = $this->getConnectionById($connectionID)) {
  130. throw new \InvalidArgumentException("Invalid connection ID: '$connectionID'");
  131. }
  132. return new static($connection, $this->options);
  133. }
  134. /**
  135. * Opens the connection to the server.
  136. */
  137. public function connect()
  138. {
  139. $this->connection->connect();
  140. }
  141. /**
  142. * Disconnects from the server.
  143. */
  144. public function disconnect()
  145. {
  146. $this->connection->disconnect();
  147. }
  148. /**
  149. * Disconnects from the server.
  150. *
  151. * This method is an alias of disconnect().
  152. */
  153. public function quit()
  154. {
  155. $this->disconnect();
  156. }
  157. /**
  158. * Checks if the underlying connection is connected to Redis.
  159. *
  160. * @return bool True means that the connection is open.
  161. * False means that the connection is closed.
  162. */
  163. public function isConnected()
  164. {
  165. return $this->connection->isConnected();
  166. }
  167. /**
  168. * {@inheritdoc}
  169. */
  170. public function getConnection()
  171. {
  172. return $this->connection;
  173. }
  174. /**
  175. * Retrieves a single connection out of an aggregated connections instance.
  176. *
  177. * @param string $connectionId Index or alias of the single connection.
  178. * @return Connection\SingleConnectionInterface
  179. */
  180. public function getConnectionById($connectionId)
  181. {
  182. if (!$this->connection instanceof AggregatedConnectionInterface) {
  183. throw new NotSupportedException('Retrieving connections by ID is supported only when using aggregated connections');
  184. }
  185. return $this->connection->getConnectionById($connectionId);
  186. }
  187. /**
  188. * Creates a Redis command with the specified arguments and sends a request
  189. * to the server.
  190. *
  191. * @param string $commandID Command ID.
  192. * @param array $arguments Arguments for the command.
  193. * @return mixed
  194. */
  195. public function __call($commandID, $arguments)
  196. {
  197. $command = $this->createCommand($commandID, $arguments);
  198. $response = $this->executeCommand($command);
  199. return $response;
  200. }
  201. /**
  202. * {@inheritdoc}
  203. */
  204. public function createCommand($commandID, $arguments = array())
  205. {
  206. return $this->profile->createCommand($commandID, $arguments);
  207. }
  208. /**
  209. * {@inheritdoc}
  210. */
  211. public function executeCommand(CommandInterface $command)
  212. {
  213. $response = $this->connection->executeCommand($command);
  214. if ($response instanceof ResponseObjectInterface) {
  215. if ($response instanceof ResponseErrorInterface) {
  216. $response = $this->onResponseError($command, $response);
  217. }
  218. return $response;
  219. }
  220. return $command->parseResponse($response);
  221. }
  222. /**
  223. * Handles -ERR responses returned by Redis.
  224. *
  225. * @param CommandInterface $command The command that generated the error.
  226. * @param ResponseErrorInterface $response The error response instance.
  227. * @return mixed
  228. */
  229. protected function onResponseError(CommandInterface $command, ResponseErrorInterface $response)
  230. {
  231. if ($command instanceof ScriptedCommand && $response->getErrorType() === 'NOSCRIPT') {
  232. $eval = $this->createCommand('eval');
  233. $eval->setRawArguments($command->getEvalArguments());
  234. $response = $this->executeCommand($eval);
  235. if (!$response instanceof ResponseObjectInterface) {
  236. $response = $command->parseResponse($response);
  237. }
  238. return $response;
  239. }
  240. if ($this->options->exceptions) {
  241. throw new ServerException($response->getMessage());
  242. }
  243. return $response;
  244. }
  245. /**
  246. * Calls the specified initializer method on $this with 0, 1 or 2 arguments.
  247. *
  248. * TODO: Invert $argv and $initializer.
  249. *
  250. * @param array $argv Arguments for the initializer.
  251. * @param string $initializer The initializer method.
  252. * @return mixed
  253. */
  254. private function sharedInitializer($argv, $initializer)
  255. {
  256. switch (count($argv)) {
  257. case 0:
  258. return $this->$initializer();
  259. case 1:
  260. list($arg0) = $argv;
  261. return is_array($arg0) ? $this->$initializer($arg0) : $this->$initializer(null, $arg0);
  262. case 2:
  263. list($arg0, $arg1) = $argv;
  264. return $this->$initializer($arg0, $arg1);
  265. default:
  266. return $this->$initializer($this, $argv);
  267. }
  268. }
  269. /**
  270. * Creates a new pipeline context and returns it, or returns the results of
  271. * a pipeline executed inside the optionally provided callable object.
  272. *
  273. * @param mixed ... Options for the context, a callable object, or both.
  274. * @return PipelineContext|array
  275. */
  276. public function pipeline(/* arguments */)
  277. {
  278. return $this->sharedInitializer(func_get_args(), 'initPipeline');
  279. }
  280. /**
  281. * Pipeline context initializer.
  282. *
  283. * @param array $options Options for the context.
  284. * @param mixed $callable Optional callable object used to execute the context.
  285. * @return PipelineContext|array
  286. */
  287. protected function initPipeline(Array $options = null, $callable = null)
  288. {
  289. $executor = isset($options['executor']) ? $options['executor'] : null;
  290. if (is_callable($executor)) {
  291. $executor = call_user_func($executor, $this, $options);
  292. }
  293. $pipeline = new PipelineContext($this, $executor);
  294. $replies = $this->pipelineExecute($pipeline, $callable);
  295. return $replies;
  296. }
  297. /**
  298. * Executes a pipeline context when a callable object is passed.
  299. *
  300. * @param PipelineContext $pipeline Pipeline context instance.
  301. * @param mixed $callable Optional callable object used to execute the context.
  302. * @return PipelineContext|array
  303. */
  304. private function pipelineExecute(PipelineContext $pipeline, $callable)
  305. {
  306. return isset($callable) ? $pipeline->execute($callable) : $pipeline;
  307. }
  308. /**
  309. * Creates a new transaction context and returns it, or returns the results of
  310. * a transaction executed inside the optionally provided callable object.
  311. *
  312. * @deprecated You should start using the new Client::transaction() method
  313. * as it will replace Client::multiExec() in the next major
  314. * version of the library.
  315. *
  316. * @param mixed ... Options for the context, a callable object, or both.
  317. * @return MultiExecContext|array
  318. */
  319. public function multiExec(/* arguments */)
  320. {
  321. return $this->sharedInitializer(func_get_args(), 'initMultiExec');
  322. }
  323. /**
  324. * Creates a new transaction context and returns it, or returns the results of
  325. * a transaction executed inside the optionally provided callable object.
  326. *
  327. * @param mixed ... Options for the context, a callable object, or both.
  328. * @return MultiExecContext|array
  329. */
  330. public function transaction(/* arguments */)
  331. {
  332. return $this->sharedInitializer(func_get_args(), 'initMultiExec');
  333. }
  334. /**
  335. * Transaction context initializer.
  336. *
  337. * @param array $options Options for the context.
  338. * @param mixed $callable Optional callable object used to execute the context.
  339. * @return MultiExecContext|array
  340. */
  341. protected function initMultiExec(Array $options = null, $callable = null)
  342. {
  343. $transaction = new MultiExecContext($this, $options ?: array());
  344. return isset($callable) ? $transaction->execute($callable) : $transaction;
  345. }
  346. /**
  347. * Creates a new Publish / Subscribe context and returns it, or executes it
  348. * inside the optionally provided callable object.
  349. *
  350. * @deprecated This method will change in the next major release to support
  351. * the new PUBSUB command introduced in Redis 2.8. Please use
  352. * Client::pubSubLoop() to create Predis\PubSub\PubSubContext
  353. * instances from now on.
  354. *
  355. * @param mixed ... Options for the context, a callable object, or both.
  356. * @return PubSubContext|array
  357. */
  358. public function pubSub(/* arguments */)
  359. {
  360. return call_user_func_array(array($this, 'pubSubLoop'), func_get_args());
  361. }
  362. /**
  363. * Creates a new Publish / Subscribe context and returns it, or executes it
  364. * inside the optionally provided callable object.
  365. *
  366. * @param mixed ... Options for the context, a callable object, or both.
  367. * @return PubSubContext|array
  368. */
  369. public function pubSubLoop(/* arguments */)
  370. {
  371. return $this->sharedInitializer(func_get_args(), 'initPubSub');
  372. }
  373. /**
  374. * Publish / Subscribe context initializer.
  375. *
  376. * @param array $options Options for the context.
  377. * @param mixed $callable Optional callable object used to execute the context.
  378. * @return PubSubContext
  379. */
  380. protected function initPubSub(Array $options = null, $callable = null)
  381. {
  382. $pubsub = new PubSubContext($this, $options);
  383. if (!isset($callable)) {
  384. return $pubsub;
  385. }
  386. foreach ($pubsub as $message) {
  387. if (call_user_func($callable, $pubsub, $message) === false) {
  388. $pubsub->closeContext();
  389. }
  390. }
  391. }
  392. /**
  393. * Returns a new monitor context.
  394. *
  395. * @return MonitorContext
  396. */
  397. public function monitor()
  398. {
  399. return new MonitorContext($this);
  400. }
  401. }