Client.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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. /**
  22. * Main class that exposes the most high-level interface to interact with Redis.
  23. *
  24. * @author Daniele Alessandri <suppakilla@gmail.com>
  25. */
  26. class Client implements ClientInterface
  27. {
  28. const VERSION = '0.8.0-dev';
  29. private $options;
  30. private $profile;
  31. private $connection;
  32. private $connections;
  33. /**
  34. * Initializes a new client with optional connection parameters and client options.
  35. *
  36. * @param mixed $parameters Connection parameters for one or multiple servers.
  37. * @param mixed $options Options that specify certain behaviours for the client.
  38. */
  39. public function __construct($parameters = null, $options = null)
  40. {
  41. $options = $this->filterOptions($options);
  42. $this->options = $options;
  43. $this->profile = $options->profile;
  44. $this->connections = $options->connections;
  45. $this->connection = $this->initializeConnection($parameters);
  46. }
  47. /**
  48. * Creates an instance of Predis\Option\ClientOptions from various types of
  49. * arguments (string, array, Predis\Profile\ServerProfile) or returns the
  50. * passed object if it is an instance of Predis\Option\ClientOptions.
  51. *
  52. * @param mixed $options Client options.
  53. * @return ClientOptions
  54. */
  55. protected function filterOptions($options)
  56. {
  57. if ($options === null) {
  58. return new ClientOptions();
  59. }
  60. if (is_array($options)) {
  61. return new ClientOptions($options);
  62. }
  63. if ($options instanceof ClientOptionsInterface) {
  64. return $options;
  65. }
  66. if ($options instanceof ServerProfileInterface || is_string($options)) {
  67. return new ClientOptions(array('profile' => $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, $this->profile);
  88. }
  89. return $this->connections->create($parameters, $this->profile);
  90. }
  91. /**
  92. * {@inheritdoc}
  93. */
  94. public function getProfile()
  95. {
  96. return $this->profile;
  97. }
  98. /**
  99. * {@inheritdoc}
  100. */
  101. public function getOptions()
  102. {
  103. return $this->options;
  104. }
  105. /**
  106. * Returns the connection factory object used by the client.
  107. *
  108. * @return ConnectionFactoryInterface
  109. */
  110. public function getConnectionFactory()
  111. {
  112. return $this->connections;
  113. }
  114. /**
  115. * Returns a new instance of a client for the specified connection when the
  116. * client is connected to a cluster. The new instance will use the same
  117. * options of the original client.
  118. *
  119. * @return Client
  120. */
  121. public function getClientFor($connectionAlias)
  122. {
  123. if (($connection = $this->getConnection($connectionAlias)) === null) {
  124. throw new \InvalidArgumentException("Invalid connection alias: '$connectionAlias'");
  125. }
  126. return new Client($connection, $this->options);
  127. }
  128. /**
  129. * Opens the connection to the server.
  130. */
  131. public function connect()
  132. {
  133. $this->connection->connect();
  134. }
  135. /**
  136. * Disconnects from the server.
  137. */
  138. public function disconnect()
  139. {
  140. $this->connection->disconnect();
  141. }
  142. /**
  143. * Disconnects from the server.
  144. *
  145. * This method is an alias of disconnect().
  146. */
  147. public function quit()
  148. {
  149. $this->disconnect();
  150. }
  151. /**
  152. * Checks if the underlying connection is connected to Redis.
  153. *
  154. * @return Boolean True means that the connection is open.
  155. * False means that the connection is closed.
  156. */
  157. public function isConnected()
  158. {
  159. return $this->connection->isConnected();
  160. }
  161. /**
  162. * {@inheritdoc}
  163. */
  164. public function getConnection($id = null)
  165. {
  166. if (isset($id)) {
  167. if (!Helpers::isAggregated($this->connection)) {
  168. $message = 'Retrieving connections by alias is supported only with aggregated connections (cluster or replication)';
  169. throw new NotSupportedException($message);
  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. return $this->connection->executeCommand($command);
  186. }
  187. /**
  188. * {@inheritdoc}
  189. */
  190. public function createCommand($method, $arguments = array())
  191. {
  192. return $this->profile->createCommand($method, $arguments);
  193. }
  194. /**
  195. * {@inheritdoc}
  196. */
  197. public function executeCommand(CommandInterface $command)
  198. {
  199. return $this->connection->executeCommand($command);
  200. }
  201. /**
  202. * Calls the specified initializer method on $this with 0, 1 or 2 arguments.
  203. *
  204. * TODO: Invert $argv and $initializer.
  205. *
  206. * @param array $argv Arguments for the initializer.
  207. * @param string $initializer The initializer method.
  208. * @return mixed
  209. */
  210. private function sharedInitializer($argv, $initializer)
  211. {
  212. switch (count($argv)) {
  213. case 0:
  214. return $this->$initializer();
  215. case 1:
  216. list($arg0) = $argv;
  217. return is_array($arg0) ? $this->$initializer($arg0) : $this->$initializer(null, $arg0);
  218. case 2:
  219. list($arg0, $arg1) = $argv;
  220. return $this->$initializer($arg0, $arg1);
  221. default:
  222. return $this->$initializer($this, $argv);
  223. }
  224. }
  225. /**
  226. * Creates a new pipeline context and returns it, or returns the results of
  227. * a pipeline executed inside the optionally provided callable object.
  228. *
  229. * @param mixed $arg,... Options for the context, a callable object, or both.
  230. * @return PipelineContext|array
  231. */
  232. public function pipeline(/* arguments */)
  233. {
  234. return $this->sharedInitializer(func_get_args(), 'initPipeline');
  235. }
  236. /**
  237. * Pipeline context initializer.
  238. *
  239. * @param array $options Options for the context.
  240. * @param mixed $callable Optional callable object used to execute the context.
  241. * @return PipelineContext|array
  242. */
  243. protected function initPipeline(Array $options = null, $callable = null)
  244. {
  245. $pipeline = new PipelineContext($this, $options);
  246. return $this->pipelineExecute($pipeline, $callable);
  247. }
  248. /**
  249. * Executes a pipeline context when a callable object is passed.
  250. *
  251. * @param array $options Options of the context initialization.
  252. * @param mixed $callable Optional callable object used to execute the context.
  253. * @return PipelineContext|array
  254. */
  255. private function pipelineExecute(PipelineContext $pipeline, $callable)
  256. {
  257. return isset($callable) ? $pipeline->execute($callable) : $pipeline;
  258. }
  259. /**
  260. * Creates a new transaction context and returns it, or returns the results of
  261. * a transaction executed inside the optionally provided callable object.
  262. *
  263. * @param mixed $arg,... Options for the context, a callable object, or both.
  264. * @return MultiExecContext|array
  265. */
  266. public function multiExec(/* arguments */)
  267. {
  268. return $this->sharedInitializer(func_get_args(), 'initMultiExec');
  269. }
  270. /**
  271. * Transaction context initializer.
  272. *
  273. * @param array $options Options for the context.
  274. * @param mixed $callable Optional callable object used to execute the context.
  275. * @return MultiExecContext|array
  276. */
  277. protected function initMultiExec(Array $options = null, $callable = null)
  278. {
  279. $transaction = new MultiExecContext($this, $options ?: array());
  280. return isset($callable) ? $transaction->execute($callable) : $transaction;
  281. }
  282. /**
  283. * Creates a new Publish / Subscribe context and returns it, or executes it
  284. * inside the optionally provided callable object.
  285. *
  286. * @param mixed $arg,... Options for the context, a callable object, or both.
  287. * @return MultiExecContext|array
  288. */
  289. public function pubSub(/* arguments */)
  290. {
  291. return $this->sharedInitializer(func_get_args(), 'initPubSub');
  292. }
  293. /**
  294. * Publish / Subscribe context initializer.
  295. *
  296. * @param array $options Options for the context.
  297. * @param mixed $callable Optional callable object used to execute the context.
  298. * @return PubSubContext
  299. */
  300. protected function initPubSub(Array $options = null, $callable = null)
  301. {
  302. $pubsub = new PubSubContext($this, $options);
  303. if (!isset($callable)) {
  304. return $pubsub;
  305. }
  306. foreach ($pubsub as $message) {
  307. if (call_user_func($callable, $pubsub, $message) === false) {
  308. $pubsub->closeContext();
  309. }
  310. }
  311. }
  312. /**
  313. * Returns a new monitor context.
  314. *
  315. * @return MonitorContext
  316. */
  317. public function monitor()
  318. {
  319. return new MonitorContext($this);
  320. }
  321. }