Client.php 13 KB

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