Client.php 12 KB

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