ConnectionCluster.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. if ($command->canBeHashed() === false) {
  42. throw new ClientException(
  43. sprintf("Cannot send '%s' commands to a cluster of connections", $command->getId())
  44. );
  45. }
  46. return $this->_distributor->get($command->getHash($this->_distributor));
  47. }
  48. public function getConnectionById($id = null) {
  49. $alias = $id ?: 0;
  50. return isset($this->_pool[$alias]) ? $this->_pool[$alias] : null;
  51. }
  52. public function getIterator() {
  53. return new \ArrayIterator($this->_pool);
  54. }
  55. public function writeCommand(ICommand $command) {
  56. $this->getConnection($command)->writeCommand($command);
  57. }
  58. public function readResponse(ICommand $command) {
  59. return $this->getConnection($command)->readResponse($command);
  60. }
  61. public function executeCommand(ICommand $command) {
  62. $connection = $this->getConnection($command);
  63. $connection->writeCommand($command);
  64. return $connection->readResponse($command);
  65. }
  66. }