Client.php 12 KB

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