Client.php 13 KB

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