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\Commands\ICommand;
  12. use Predis\Network\IConnection;
  13. use Predis\Network\IConnectionSingle;
  14. use Predis\Profiles\IServerProfile;
  15. use Predis\Profiles\ServerProfile;
  16. use Predis\PubSub\PubSubContext;
  17. use Predis\Pipeline\PipelineContext;
  18. use Predis\Transaction\MultiExecContext;
  19. /**
  20. * Main class that exposes the most high-level interface to interact with Redis.
  21. *
  22. * @author Daniele Alessandri <suppakilla@gmail.com>
  23. */
  24. class Client
  25. {
  26. const VERSION = '0.7.0-dev';
  27. private $options;
  28. private $profile;
  29. private $connection;
  30. private $connectionFactory;
  31. /**
  32. * Initializes a new client with optional connection parameters and client options.
  33. *
  34. * @param mixed $parameters Connection parameters for one or multiple servers.
  35. * @param mixed $options Options that specify certain behaviours for the client.
  36. */
  37. public function __construct($parameters = null, $options = null)
  38. {
  39. $options = $this->filterOptions($options);
  40. $profile = $options->profile;
  41. if (isset($options->prefix)) {
  42. $profile->setProcessor($options->prefix);
  43. }
  44. $this->options = $options;
  45. $this->profile = $profile;
  46. $this->connectionFactory = $options->connections;
  47. $this->connection = $this->initializeConnection($parameters);
  48. }
  49. /**
  50. * Creates an instance of Predis\Options\ClientOptions from various types of
  51. * arguments (string, array, Predis\Profiles\ServerProfile) or returns the
  52. * passed object if it is an instance of Predis\Options\ClientOptions.
  53. *
  54. * @param mixed $options Client options.
  55. * @return ClientOptions
  56. */
  57. private function filterOptions($options)
  58. {
  59. if ($options === null) {
  60. return new ClientOptions();
  61. }
  62. if (is_array($options)) {
  63. return new ClientOptions($options);
  64. }
  65. if ($options instanceof ClientOptions) {
  66. return $options;
  67. }
  68. if ($options instanceof IServerProfile) {
  69. return new ClientOptions(array('profile' => $options));
  70. }
  71. if (is_string($options)) {
  72. return new ClientOptions(array('profile' => ServerProfile::get($options)));
  73. }
  74. throw new \InvalidArgumentException("Invalid type for client options");
  75. }
  76. /**
  77. * Initializes one or multiple connection (cluster) objects from various
  78. * types of arguments (string, array) or returns the passed object if it
  79. * implements the Predis\Network\IConnection interface.
  80. *
  81. * @param mixed $parameters Connection parameters or instance.
  82. * @return IConnection
  83. */
  84. private function initializeConnection($parameters)
  85. {
  86. if ($parameters === null) {
  87. return $this->createConnection(new ConnectionParameters());
  88. }
  89. if (is_array($parameters)) {
  90. if (isset($parameters[0])) {
  91. $cluster = $this->options->cluster;
  92. foreach ($parameters as $node) {
  93. $connection = $node instanceof IConnectionSingle ? $node : $this->createConnection($node);
  94. $cluster->add($connection);
  95. }
  96. return $cluster;
  97. }
  98. return $this->createConnection($parameters);
  99. }
  100. if ($parameters instanceof IConnection) {
  101. return $parameters;
  102. }
  103. return $this->createConnection($parameters);
  104. }
  105. /**
  106. * Creates a new connection to a single server with the provided parameters.
  107. *
  108. * @param mixed $parameters Connection parameters.
  109. * @return IConnectionSingle
  110. */
  111. protected function createConnection($parameters)
  112. {
  113. $connection = $this->connectionFactory->create($parameters);
  114. $parameters = $connection->getParameters();
  115. if (isset($parameters->password)) {
  116. $command = $this->createCommand('auth', array($parameters->password));
  117. $connection->pushInitCommand($command);
  118. }
  119. if (isset($parameters->database)) {
  120. $command = $this->createCommand('select', array($parameters->database));
  121. $connection->pushInitCommand($command);
  122. }
  123. return $connection;
  124. }
  125. /**
  126. * Returns the server profile used by the client.
  127. *
  128. * @return IServerProfile
  129. */
  130. public function getProfile()
  131. {
  132. return $this->profile;
  133. }
  134. /**
  135. * Returns the client options specified upon initialization.
  136. *
  137. * @return ClientOptions
  138. */
  139. public function getOptions()
  140. {
  141. return $this->options;
  142. }
  143. /**
  144. * Returns the connection factory object used by the client.
  145. *
  146. * @return IConnectionFactory
  147. */
  148. public function getConnectionFactory()
  149. {
  150. return $this->connectionFactory;
  151. }
  152. /**
  153. * Returns a new instance of a client for the specified connection when the
  154. * client is connected to a cluster. The new instance will use the same
  155. * options of the original client.
  156. *
  157. * @return Client
  158. */
  159. public function getClientFor($connectionAlias)
  160. {
  161. if (($connection = $this->getConnection($connectionAlias)) === null) {
  162. throw new \InvalidArgumentException("Invalid connection alias: '$connectionAlias'");
  163. }
  164. return new Client($connection, $this->options);
  165. }
  166. /**
  167. * Opens the connection to the server.
  168. */
  169. public function connect()
  170. {
  171. $this->connection->connect();
  172. }
  173. /**
  174. * Disconnects from the server.
  175. */
  176. public function disconnect()
  177. {
  178. $this->connection->disconnect();
  179. }
  180. /**
  181. * Disconnects from the server.
  182. *
  183. * This method is an alias of disconnect().
  184. */
  185. public function quit()
  186. {
  187. $this->disconnect();
  188. }
  189. /**
  190. * Checks if the underlying connection is connected to Redis.
  191. *
  192. * @return Boolean True means that the connection is open.
  193. * False means that the connection is closed.
  194. */
  195. public function isConnected()
  196. {
  197. return $this->connection->isConnected();
  198. }
  199. /**
  200. * Returns the underlying connection instance or, when connected to a cluster,
  201. * one of the connection instances identified by its alias.
  202. *
  203. * @param string $id The alias of a connection when connected to a cluster.
  204. * @return IConnection
  205. */
  206. public function getConnection($id = null)
  207. {
  208. if (isset($id)) {
  209. if (!Helpers::isCluster($this->connection)) {
  210. throw new ClientException(
  211. 'Retrieving connections by alias is supported only with clustered connections'
  212. );
  213. }
  214. return $this->connection->getConnectionById($id);
  215. }
  216. return $this->connection;
  217. }
  218. /**
  219. * Dinamically invokes a Redis command with the specified arguments.
  220. *
  221. * @param string $method The name of a Redis command.
  222. * @param array $arguments The arguments for the command.
  223. * @return mixed
  224. */
  225. public function __call($method, $arguments)
  226. {
  227. $command = $this->profile->createCommand($method, $arguments);
  228. return $this->connection->executeCommand($command);
  229. }
  230. /**
  231. * Creates a new instance of the specified Redis command.
  232. *
  233. * @param string $method The name of a Redis command.
  234. * @param array $arguments The arguments for the command.
  235. * @return ICommand
  236. */
  237. public function createCommand($method, $arguments = array())
  238. {
  239. return $this->profile->createCommand($method, $arguments);
  240. }
  241. /**
  242. * Executes the specified Redis command.
  243. *
  244. * @param ICommand $command A Redis command.
  245. * @return mixed
  246. */
  247. public function executeCommand(ICommand $command)
  248. {
  249. return $this->connection->executeCommand($command);
  250. }
  251. /**
  252. * Executes the specified Redis command on all the nodes of a cluster.
  253. *
  254. * @param ICommand $command A Redis command.
  255. * @return array
  256. */
  257. public function executeCommandOnShards(ICommand $command)
  258. {
  259. if (Helpers::isCluster($this->connection)) {
  260. $replies = array();
  261. foreach ($this->connection as $connection) {
  262. $replies[] = $connection->executeCommand($command);
  263. }
  264. return $replies;
  265. }
  266. return array($this->connection->executeCommand($command));
  267. }
  268. /**
  269. * Calls the specified initializer method on $this with 0, 1 or 2 arguments.
  270. *
  271. * TODO: Invert $argv and $initializer.
  272. *
  273. * @param array $argv Arguments for the initializer.
  274. * @param string $initializer The initializer method.
  275. * @return mixed
  276. */
  277. private function sharedInitializer($argv, $initializer)
  278. {
  279. switch (count($argv)) {
  280. case 0:
  281. return $this->$initializer();
  282. case 1:
  283. list($arg0) = $argv;
  284. return is_array($arg0) ? $this->$initializer($arg0) : $this->$initializer(null, $arg0);
  285. case 2:
  286. list($arg0, $arg1) = $argv;
  287. return $this->$initializer($arg0, $arg1);
  288. default:
  289. return $this->$initializer($this, $argv);
  290. }
  291. }
  292. /**
  293. * Creates a new pipeline context and returns it, or returns the results of
  294. * a pipeline executed inside the optionally provided callable object.
  295. *
  296. * @param mixed $arg,... Options for the context, a callable object, or both.
  297. * @return PipelineContext|array
  298. */
  299. public function pipeline(/* arguments */)
  300. {
  301. return $this->sharedInitializer(func_get_args(), 'initPipeline');
  302. }
  303. /**
  304. * Pipeline context initializer.
  305. *
  306. * @param array $options Options for the context.
  307. * @param mixed $callable Optional callable object used to execute the context.
  308. * @return PipelineContext|array
  309. */
  310. protected function initPipeline(Array $options = null, $callable = null)
  311. {
  312. $pipeline = new PipelineContext($this, $options);
  313. return $this->pipelineExecute($pipeline, $callable);
  314. }
  315. /**
  316. * Executes a pipeline context when a callable object is passed.
  317. *
  318. * @param array $options Options of the context initialization.
  319. * @param mixed $callable Optional callable object used to execute the context.
  320. * @return PipelineContext|array
  321. */
  322. private function pipelineExecute(PipelineContext $pipeline, $callable)
  323. {
  324. return isset($callable) ? $pipeline->execute($callable) : $pipeline;
  325. }
  326. /**
  327. * Creates a new transaction context and returns it, or returns the results of
  328. * a transaction executed inside the optionally provided callable object.
  329. *
  330. * @param mixed $arg,... Options for the context, a callable object, or both.
  331. * @return MultiExecContext|array
  332. */
  333. public function multiExec(/* arguments */)
  334. {
  335. return $this->sharedInitializer(func_get_args(), 'initMultiExec');
  336. }
  337. /**
  338. * Transaction 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 MultiExecContext|array
  343. */
  344. protected function initMultiExec(Array $options = null, $callable = null)
  345. {
  346. $transaction = new MultiExecContext($this, $options ?: array());
  347. return isset($callable) ? $transaction->execute($callable) : $transaction;
  348. }
  349. /**
  350. * Creates a new Publish / Subscribe context and returns it, or executes it
  351. * inside the optionally provided callable object.
  352. *
  353. * @param mixed $arg,... Options for the context, a callable object, or both.
  354. * @return MultiExecContext|array
  355. */
  356. public function pubSub(/* arguments */)
  357. {
  358. return $this->sharedInitializer(func_get_args(), 'initPubSub');
  359. }
  360. /**
  361. * Publish / Subscribe context initializer.
  362. *
  363. * @param array $options Options for the context.
  364. * @param mixed $callable Optional callable object used to execute the context.
  365. * @return PubSubContext
  366. */
  367. protected function initPubSub(Array $options = null, $callable = null)
  368. {
  369. $pubsub = new PubSubContext($this, $options);
  370. if (!isset($callable)) {
  371. return $pubsub;
  372. }
  373. foreach ($pubsub as $message) {
  374. if ($callable($pubsub, $message) === false) {
  375. $pubsub->closeContext();
  376. }
  377. }
  378. }
  379. /**
  380. * Returns a new monitor context.
  381. *
  382. * @return MonitorContext
  383. */
  384. public function monitor()
  385. {
  386. return new MonitorContext($this);
  387. }
  388. }