ConnectionCluster.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace Predis\Network;
  3. use Predis\ClientException;
  4. use Predis\Commands\ICommand;
  5. use Predis\Distribution\IDistributionStrategy;
  6. class ConnectionCluster implements IConnectionCluster, \IteratorAggregate {
  7. private $_pool, $_distributor;
  8. public function __construct(IDistributionStrategy $distributor = null) {
  9. $this->_pool = array();
  10. $this->_distributor = $distributor ?: new Distribution\HashRing();
  11. }
  12. public function isConnected() {
  13. foreach ($this->_pool as $connection) {
  14. if ($connection->isConnected()) {
  15. return true;
  16. }
  17. }
  18. return false;
  19. }
  20. public function connect() {
  21. foreach ($this->_pool as $connection) {
  22. $connection->connect();
  23. }
  24. }
  25. public function disconnect() {
  26. foreach ($this->_pool as $connection) {
  27. $connection->disconnect();
  28. }
  29. }
  30. public function add(IConnectionSingle $connection) {
  31. $parameters = $connection->getParameters();
  32. if (isset($parameters->alias)) {
  33. $this->_pool[$parameters->alias] = $connection;
  34. }
  35. else {
  36. $this->_pool[] = $connection;
  37. }
  38. $this->_distributor->add($connection, $parameters->weight);
  39. }
  40. public function getConnection(ICommand $command) {
  41. $cmdHash = $command->getHash($this->_distributor);
  42. if (isset($cmdHash)) {
  43. return $this->_distributor->get($cmdHash);
  44. }
  45. throw new ClientException(
  46. sprintf("Cannot send '%s' commands to a cluster of connections", $command->getId())
  47. );
  48. }
  49. public function getConnectionById($id = null) {
  50. $alias = $id ?: 0;
  51. return isset($this->_pool[$alias]) ? $this->_pool[$alias] : null;
  52. }
  53. public function getIterator() {
  54. return new \ArrayIterator($this->_pool);
  55. }
  56. public function writeCommand(ICommand $command) {
  57. $this->getConnection($command)->writeCommand($command);
  58. }
  59. public function readResponse(ICommand $command) {
  60. return $this->getConnection($command)->readResponse($command);
  61. }
  62. public function executeCommand(ICommand $command) {
  63. return $this->getConnection($command)->executeCommand($command);
  64. }
  65. }