Client.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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. $profile = $options->profile;
  43. if (isset($options->prefix)) {
  44. $profile->setProcessor($options->prefix);
  45. }
  46. $this->options = $options;
  47. $this->profile = $profile;
  48. $this->connections = $options->connections;
  49. $this->connection = $this->initializeConnection($parameters);
  50. }
  51. /**
  52. * Creates an instance of Predis\Options\ClientOptions from various types of
  53. * arguments (string, array, Predis\Profiles\ServerProfile) or returns the
  54. * passed object if it is an instance of Predis\Options\ClientOptions.
  55. *
  56. * @param mixed $options Client options.
  57. * @return ClientOptions
  58. */
  59. protected function filterOptions($options)
  60. {
  61. if ($options === null) {
  62. return new ClientOptions();
  63. }
  64. if (is_array($options)) {
  65. return new ClientOptions($options);
  66. }
  67. if ($options instanceof IClientOptions) {
  68. return $options;
  69. }
  70. if ($options instanceof IServerProfile) {
  71. return new ClientOptions(array('profile' => $options));
  72. }
  73. if (is_string($options)) {
  74. return new ClientOptions(array('profile' => ServerProfile::get($options)));
  75. }
  76. throw new \InvalidArgumentException("Invalid type for client options");
  77. }
  78. /**
  79. * Initializes one or multiple connection (cluster) objects from various
  80. * types of arguments (string, array) or returns the passed object if it
  81. * implements the Predis\Network\IConnection interface.
  82. *
  83. * @param mixed $parameters Connection parameters or instance.
  84. * @return IConnection
  85. */
  86. protected function initializeConnection($parameters)
  87. {
  88. if ($parameters instanceof IConnection) {
  89. return $parameters;
  90. }
  91. if (is_array($parameters) && isset($parameters[0])) {
  92. return $this->connections->createCluster($this->options->cluster, $parameters, $this->profile);
  93. }
  94. return $this->connections->create($parameters, $this->profile);
  95. }
  96. /**
  97. * Returns the server profile used by the client.
  98. *
  99. * @return IServerProfile
  100. */
  101. public function getProfile()
  102. {
  103. return $this->profile;
  104. }
  105. /**
  106. * Returns the client options specified upon initialization.
  107. *
  108. * @return ClientOptions
  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 IConnectionFactory
  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($connectionAlias)
  131. {
  132. if (($connection = $this->getConnection($connectionAlias)) === null) {
  133. throw new \InvalidArgumentException("Invalid connection alias: '$connectionAlias'");
  134. }
  135. return new Client($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. * Returns the underlying connection instance or, when connected to a cluster,
  172. * one of the connection instances identified by its alias.
  173. *
  174. * @param string $id The alias of a connection when connected to a cluster.
  175. * @return IConnection
  176. */
  177. public function getConnection($id = null)
  178. {
  179. if (isset($id)) {
  180. if (!Helpers::isCluster($this->connection)) {
  181. throw new ClientException(
  182. 'Retrieving connections by alias is supported only with clustered connections'
  183. );
  184. }
  185. return $this->connection->getConnectionById($id);
  186. }
  187. return $this->connection;
  188. }
  189. /**
  190. * Dinamically invokes a Redis command with the specified arguments.
  191. *
  192. * @param string $method The name of a Redis command.
  193. * @param array $arguments The arguments for the command.
  194. * @return mixed
  195. */
  196. public function __call($method, $arguments)
  197. {
  198. $command = $this->profile->createCommand($method, $arguments);
  199. return $this->connection->executeCommand($command);
  200. }
  201. /**
  202. * Creates a new instance of the specified Redis command.
  203. *
  204. * @param string $method The name of a Redis command.
  205. * @param array $arguments The arguments for the command.
  206. * @return ICommand
  207. */
  208. public function createCommand($method, $arguments = array())
  209. {
  210. return $this->profile->createCommand($method, $arguments);
  211. }
  212. /**
  213. * Executes the specified Redis command.
  214. *
  215. * @param ICommand $command A Redis command.
  216. * @return mixed
  217. */
  218. public function executeCommand(ICommand $command)
  219. {
  220. return $this->connection->executeCommand($command);
  221. }
  222. /**
  223. * Executes the specified Redis command on all the nodes of a cluster.
  224. *
  225. * @param ICommand $command A Redis command.
  226. * @return array
  227. */
  228. public function executeCommandOnShards(ICommand $command)
  229. {
  230. if (Helpers::isCluster($this->connection)) {
  231. $replies = array();
  232. foreach ($this->connection as $connection) {
  233. $replies[] = $connection->executeCommand($command);
  234. }
  235. return $replies;
  236. }
  237. return array($this->connection->executeCommand($command));
  238. }
  239. /**
  240. * Calls the specified initializer method on $this with 0, 1 or 2 arguments.
  241. *
  242. * TODO: Invert $argv and $initializer.
  243. *
  244. * @param array $argv Arguments for the initializer.
  245. * @param string $initializer The initializer method.
  246. * @return mixed
  247. */
  248. private function sharedInitializer($argv, $initializer)
  249. {
  250. switch (count($argv)) {
  251. case 0:
  252. return $this->$initializer();
  253. case 1:
  254. list($arg0) = $argv;
  255. return is_array($arg0) ? $this->$initializer($arg0) : $this->$initializer(null, $arg0);
  256. case 2:
  257. list($arg0, $arg1) = $argv;
  258. return $this->$initializer($arg0, $arg1);
  259. default:
  260. return $this->$initializer($this, $argv);
  261. }
  262. }
  263. /**
  264. * Creates a new pipeline context and returns it, or returns the results of
  265. * a pipeline executed inside the optionally provided callable object.
  266. *
  267. * @param mixed $arg,... Options for the context, a callable object, or both.
  268. * @return PipelineContext|array
  269. */
  270. public function pipeline(/* arguments */)
  271. {
  272. return $this->sharedInitializer(func_get_args(), 'initPipeline');
  273. }
  274. /**
  275. * Pipeline context initializer.
  276. *
  277. * @param array $options Options for the context.
  278. * @param mixed $callable Optional callable object used to execute the context.
  279. * @return PipelineContext|array
  280. */
  281. protected function initPipeline(Array $options = null, $callable = null)
  282. {
  283. $pipeline = new PipelineContext($this, $options);
  284. return $this->pipelineExecute($pipeline, $callable);
  285. }
  286. /**
  287. * Executes a pipeline context when a callable object is passed.
  288. *
  289. * @param array $options Options of the context initialization.
  290. * @param mixed $callable Optional callable object used to execute the context.
  291. * @return PipelineContext|array
  292. */
  293. private function pipelineExecute(PipelineContext $pipeline, $callable)
  294. {
  295. return isset($callable) ? $pipeline->execute($callable) : $pipeline;
  296. }
  297. /**
  298. * Creates a new transaction context and returns it, or returns the results of
  299. * a transaction executed inside the optionally provided callable object.
  300. *
  301. * @param mixed $arg,... Options for the context, a callable object, or both.
  302. * @return MultiExecContext|array
  303. */
  304. public function multiExec(/* arguments */)
  305. {
  306. return $this->sharedInitializer(func_get_args(), 'initMultiExec');
  307. }
  308. /**
  309. * Transaction context initializer.
  310. *
  311. * @param array $options Options for the context.
  312. * @param mixed $callable Optional callable object used to execute the context.
  313. * @return MultiExecContext|array
  314. */
  315. protected function initMultiExec(Array $options = null, $callable = null)
  316. {
  317. $transaction = new MultiExecContext($this, $options ?: array());
  318. return isset($callable) ? $transaction->execute($callable) : $transaction;
  319. }
  320. /**
  321. * Creates a new Publish / Subscribe context and returns it, or executes it
  322. * inside the optionally provided callable object.
  323. *
  324. * @param mixed $arg,... Options for the context, a callable object, or both.
  325. * @return MultiExecContext|array
  326. */
  327. public function pubSub(/* arguments */)
  328. {
  329. return $this->sharedInitializer(func_get_args(), 'initPubSub');
  330. }
  331. /**
  332. * Publish / Subscribe context initializer.
  333. *
  334. * @param array $options Options for the context.
  335. * @param mixed $callable Optional callable object used to execute the context.
  336. * @return PubSubContext
  337. */
  338. protected function initPubSub(Array $options = null, $callable = null)
  339. {
  340. $pubsub = new PubSubContext($this, $options);
  341. if (!isset($callable)) {
  342. return $pubsub;
  343. }
  344. foreach ($pubsub as $message) {
  345. if ($callable($pubsub, $message) === false) {
  346. $pubsub->closeContext();
  347. }
  348. }
  349. }
  350. /**
  351. * Returns a new monitor context.
  352. *
  353. * @return MonitorContext
  354. */
  355. public function monitor()
  356. {
  357. return new MonitorContext($this);
  358. }
  359. }