Client.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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 InvalidArgumentException;
  12. use Predis\Command\CommandInterface;
  13. use Predis\Command\ScriptedCommand;
  14. use Predis\Configuration\Options;
  15. use Predis\Configuration\OptionsInterface;
  16. use Predis\Connection\AggregatedConnectionInterface;
  17. use Predis\Connection\ConnectionInterface;
  18. use Predis\Connection\ConnectionFactoryInterface;
  19. use Predis\Connection\ConnectionParametersInterface;
  20. use Predis\Monitor\MonitorContext;
  21. use Predis\Pipeline\PipelineContext;
  22. use Predis\Profile\ServerProfile;
  23. use Predis\PubSub\PubSubContext;
  24. use Predis\Transaction\MultiExecContext;
  25. /**
  26. * Client class used for connecting and executing commands on Redis.
  27. *
  28. * This is the main high-level abstraction of Predis upon which various other
  29. * abstractions are built. Internally it aggregates various other classes each
  30. * one with its own responsibility and scope.
  31. *
  32. * @author Daniele Alessandri <suppakilla@gmail.com>
  33. */
  34. class Client implements ClientInterface
  35. {
  36. const VERSION = '0.9.0-dev';
  37. protected $connection;
  38. protected $options;
  39. private $profile;
  40. /**
  41. * @param mixed $parameters Connection parameters for one or more servers.
  42. * @param mixed $options Options to configure some behaviours of the client.
  43. */
  44. public function __construct($parameters = null, $options = null)
  45. {
  46. $this->options = $this->createOptions($options ?: array());
  47. $this->connection = $this->createConnection($parameters ?: array());
  48. $this->profile = $this->options->profile;
  49. }
  50. /**
  51. * Creates a new instance of Predis\Configuration\Options from different
  52. * types of arguments or simply returns the passed argument if it is an
  53. * instance of Predis\Configuration\OptionsInterface.
  54. *
  55. * @param mixed $options Client options.
  56. * @return OptionsInterface
  57. */
  58. protected function createOptions($options)
  59. {
  60. if (is_array($options)) {
  61. return new Options($options);
  62. }
  63. if ($options instanceof OptionsInterface) {
  64. return $options;
  65. }
  66. throw new InvalidArgumentException("Invalid type for client options");
  67. }
  68. /**
  69. * Creates single or aggregate connections from different types of arguments
  70. * (string, array) or returns the passed argument if it is an instance of a
  71. * class implementing Predis\Connection\ConnectionInterface.
  72. *
  73. * Accepted types for connection parameters are:
  74. *
  75. * - Instance of Predis\Connection\ConnectionInterface.
  76. * - Instance of Predis\Connection\ConnectionParametersInterface.
  77. * - Array
  78. * - String
  79. * - Callable
  80. *
  81. * @param mixed $parameters Connection parameters or connection instance.
  82. * @return ConnectionInterface
  83. */
  84. protected function createConnection($parameters)
  85. {
  86. if ($parameters instanceof ConnectionInterface) {
  87. return $parameters;
  88. }
  89. if ($parameters instanceof ConnectionParametersInterface || is_string($parameters)) {
  90. return $this->options->connections->create($parameters);
  91. }
  92. if (is_array($parameters)) {
  93. $options = $this->options;
  94. if (isset($parameters[0])) {
  95. $replication = isset($options->replication) && $options->replication;
  96. $connection = $options->{$replication ? 'replication' : 'cluster'};
  97. $options->connections->aggregate($connection, $parameters);
  98. return $connection;
  99. }
  100. return $options->connections->create($parameters);
  101. }
  102. if (is_callable($parameters)) {
  103. $connection = call_user_func($parameters, $this->options);
  104. if (!$connection instanceof ConnectionInterface) {
  105. throw new InvalidArgumentException(
  106. 'Callable parameters must return instances of Predis\Connection\ConnectionInterface'
  107. );
  108. }
  109. return $connection;
  110. }
  111. throw new InvalidArgumentException('Invalid type for connection parameters');
  112. }
  113. /**
  114. * {@inheritdoc}
  115. */
  116. public function getProfile()
  117. {
  118. return $this->profile;
  119. }
  120. /**
  121. * {@inheritdoc}
  122. */
  123. public function getOptions()
  124. {
  125. return $this->options;
  126. }
  127. /**
  128. * Creates a new client instance for the specified connection ID or alias,
  129. * only when working with an aggregate connection (cluster, replication).
  130. * The new client instances uses the same options of the original one.
  131. *
  132. * @return Client
  133. */
  134. public function getClientFor($connectionID)
  135. {
  136. if (!$connection = $this->getConnectionById($connectionID)) {
  137. throw new InvalidArgumentException("Invalid connection ID: $connectionID");
  138. }
  139. return new static($connection, $this->options);
  140. }
  141. /**
  142. * Opens the underlying connection and connects to the server.
  143. */
  144. public function connect()
  145. {
  146. $this->connection->connect();
  147. }
  148. /**
  149. * Closes the underlying connection and disconnect from the server.
  150. */
  151. public function disconnect()
  152. {
  153. $this->connection->disconnect();
  154. }
  155. /**
  156. * Closes the underlying connection and disconnect from the server.
  157. *
  158. * This is the same as `Client::disconnect()` as it does not actually send
  159. * the `QUIT` command to Redis, but simply closes the connection.
  160. */
  161. public function quit()
  162. {
  163. $this->disconnect();
  164. }
  165. /**
  166. * Returns the current state of the underlying connection.
  167. *
  168. * @return bool
  169. */
  170. public function isConnected()
  171. {
  172. return $this->connection->isConnected();
  173. }
  174. /**
  175. * {@inheritdoc}
  176. */
  177. public function getConnection()
  178. {
  179. return $this->connection;
  180. }
  181. /**
  182. * Retrieves the specified connection from the aggregate connection when the
  183. * client is in cluster or replication mode.
  184. *
  185. * @param string $connectionID Index or alias of the single connection.
  186. * @return Connection\SingleConnectionInterface
  187. */
  188. public function getConnectionById($connectionID)
  189. {
  190. if (!$this->connection instanceof AggregatedConnectionInterface) {
  191. throw new NotSupportedException(
  192. 'Retrieving connections by ID is supported only when using aggregated connections'
  193. );
  194. }
  195. return $this->connection->getConnectionById($connectionID);
  196. }
  197. /**
  198. * Creates a Redis command with the specified arguments and sends a request
  199. * to the server.
  200. *
  201. * @param string $commandID Command ID.
  202. * @param array $arguments Arguments for the command.
  203. * @return mixed
  204. */
  205. public function __call($commandID, $arguments)
  206. {
  207. $command = $this->createCommand($commandID, $arguments);
  208. $response = $this->executeCommand($command);
  209. return $response;
  210. }
  211. /**
  212. * {@inheritdoc}
  213. */
  214. public function createCommand($commandID, $arguments = array())
  215. {
  216. return $this->profile->createCommand($commandID, $arguments);
  217. }
  218. /**
  219. * {@inheritdoc}
  220. */
  221. public function executeCommand(CommandInterface $command)
  222. {
  223. $response = $this->connection->executeCommand($command);
  224. if ($response instanceof ResponseObjectInterface) {
  225. if ($response instanceof ResponseErrorInterface) {
  226. $response = $this->onResponseError($command, $response);
  227. }
  228. return $response;
  229. }
  230. return $command->parseResponse($response);
  231. }
  232. /**
  233. * Handles -ERR responses returned by Redis.
  234. *
  235. * @param CommandInterface $command Redis command that generated the error.
  236. * @param ResponseErrorInterface $response Instance of the error response.
  237. * @return mixed
  238. */
  239. protected function onResponseError(CommandInterface $command, ResponseErrorInterface $response)
  240. {
  241. if ($command instanceof ScriptedCommand && $response->getErrorType() === 'NOSCRIPT') {
  242. $eval = $this->createCommand('eval');
  243. $eval->setRawArguments($command->getEvalArguments());
  244. $response = $this->executeCommand($eval);
  245. if (!$response instanceof ResponseObjectInterface) {
  246. $response = $command->parseResponse($response);
  247. }
  248. return $response;
  249. }
  250. if ($this->options->exceptions) {
  251. throw new ServerException($response->getMessage());
  252. }
  253. return $response;
  254. }
  255. /**
  256. * Executes the specified initializer method on `$this` by adjusting the
  257. * actual invokation depending on the arity (0, 1 or 2 arguments). This is
  258. * simply an utility method to create Redis contexts instances since they
  259. * follow a common initialization path.
  260. *
  261. * @param string $initializer Method name.
  262. * @param array $argv Arguments for the method.
  263. * @return mixed
  264. */
  265. private function sharedContextFactory($initializer, $argv = null)
  266. {
  267. switch (count($argv)) {
  268. case 0:
  269. return $this->$initializer();
  270. case 1:
  271. list($arg0) = $argv;
  272. return is_array($arg0) ? $this->$initializer($arg0) : $this->$initializer(null, $arg0);
  273. case 2:
  274. list($arg0, $arg1) = $argv;
  275. return $this->$initializer($arg0, $arg1);
  276. default:
  277. return $this->$initializer($this, $argv);
  278. }
  279. }
  280. /**
  281. * Creates a new pipeline context and returns it, or returns the results of
  282. * a pipeline executed inside the optionally provided callable object.
  283. *
  284. * @param mixed $arg,... Options for the context, or a callable, or both.
  285. * @return PipelineContext|array
  286. */
  287. public function pipeline(/* arguments */)
  288. {
  289. return $this->sharedContextFactory('createPipeline', func_get_args());
  290. }
  291. /**
  292. * Actual pipeline context initializer method.
  293. *
  294. * @param array $options Options for the context.
  295. * @param mixed $callable Optional callable used to execute the context.
  296. * @return PipelineContext|array
  297. */
  298. protected function createPipeline(Array $options = null, $callable = null)
  299. {
  300. $executor = isset($options['executor']) ? $options['executor'] : null;
  301. if (is_callable($executor)) {
  302. $executor = call_user_func($executor, $this, $options);
  303. }
  304. $pipeline = new PipelineContext($this, $executor);
  305. if (isset($callable)) {
  306. return $pipeline->execute($callable);
  307. }
  308. return $pipeline;
  309. }
  310. /**
  311. * Creates a new transaction context and returns it, or returns the results
  312. * of a transaction executed inside the optionally provided callable object.
  313. *
  314. * @param mixed $arg,... Options for the context, or a callable, or both.
  315. * @return MultiExecContext|array
  316. */
  317. public function transaction(/* arguments */)
  318. {
  319. return $this->sharedContextFactory('createTransaction', func_get_args());
  320. }
  321. /**
  322. * Actual transaction context initializer method.
  323. *
  324. * @param array $options Options for the context.
  325. * @param mixed $callable Optional callable used to execute the context.
  326. * @return MultiExecContext|array
  327. */
  328. protected function createTransaction(Array $options = null, $callable = null)
  329. {
  330. $transaction = new MultiExecContext($this, $options);
  331. if (isset($callable)) {
  332. return $transaction->execute($callable);
  333. }
  334. return $transaction;
  335. }
  336. /**
  337. * Creates a new publis/subscribe context and returns it, or starts its loop
  338. * inside the optionally provided callable object.
  339. *
  340. * @param mixed $arg,... Options for the context, or a callable, or both.
  341. * @return PubSubExecContext|NULL
  342. */
  343. public function pubSubLoop(/* arguments */)
  344. {
  345. return $this->sharedContextFactory('createPubSub', func_get_args());
  346. }
  347. /**
  348. * Actual publish/subscribe context initializer method.
  349. *
  350. * @param array $options Options for the context.
  351. * @param mixed $callable Optional callable used to execute the context.
  352. * @return PubSubContext|NULL
  353. */
  354. protected function createPubSub(Array $options = null, $callable = null)
  355. {
  356. $pubsub = new PubSubContext($this, $options);
  357. if (!isset($callable)) {
  358. return $pubsub;
  359. }
  360. foreach ($pubsub as $message) {
  361. if (call_user_func($callable, $pubsub, $message) === false) {
  362. $pubsub->closeContext();
  363. }
  364. }
  365. }
  366. /**
  367. * Creates a new monitor context and returns it.
  368. *
  369. * @return MonitorContext
  370. */
  371. public function monitor()
  372. {
  373. return new MonitorContext($this);
  374. }
  375. }