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