Client.php 13 KB

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