Client.php 12 KB

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