Client.php 12 KB

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