Client.php 13 KB

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