Client.php 11 KB

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