ConnectionBase.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace Predis\Network;
  3. use Predis\Utils;
  4. use Predis\ICommand;
  5. use Predis\ConnectionParameters;
  6. use Predis\CommunicationException;
  7. use Predis\Protocols\IRedisProtocol;
  8. abstract class ConnectionBase implements IConnectionSingle {
  9. private $_cachedId;
  10. protected $_params, $_socket, $_initCmds, $_protocol;
  11. public function __construct(ConnectionParameters $parameters, IRedisProtocol $protocol) {
  12. $this->_initCmds = array();
  13. $this->_params = $parameters;
  14. $this->_protocol = $protocol;
  15. }
  16. public function __destruct() {
  17. $this->disconnect();
  18. }
  19. public function isConnected() {
  20. return is_resource($this->_socket);
  21. }
  22. protected abstract function createResource();
  23. public function connect() {
  24. if ($this->isConnected()) {
  25. throw new ClientException('Connection already estabilished');
  26. }
  27. $this->createResource();
  28. }
  29. public function disconnect() {
  30. if ($this->isConnected()) {
  31. fclose($this->_socket);
  32. }
  33. }
  34. public function pushInitCommand(ICommand $command){
  35. $this->_initCmds[] = $command;
  36. }
  37. public function executeCommand(ICommand $command) {
  38. $this->writeCommand($command);
  39. if ($command->closesConnection()) {
  40. return $this->disconnect();
  41. }
  42. return $this->readResponse($command);
  43. }
  44. protected function onCommunicationException($message, $code = null) {
  45. Utils::onCommunicationException(
  46. new CommunicationException($this, $message, $code)
  47. );
  48. }
  49. public function getResource() {
  50. if (!$this->isConnected()) {
  51. $this->connect();
  52. }
  53. return $this->_socket;
  54. }
  55. public function getParameters() {
  56. return $this->_params;
  57. }
  58. public function getProtocol() {
  59. return $this->_protocol;
  60. }
  61. public function setProtocol(IRedisProtocol $protocol) {
  62. if ($protocol === null) {
  63. throw new \InvalidArgumentException("The protocol instance cannot be a null value");
  64. }
  65. $this->_protocol = $protocol;
  66. }
  67. public function __toString() {
  68. if (!isset($this->_cachedId)) {
  69. $this->_cachedId = "{$this->_params->host}:{$this->_params->port}";
  70. }
  71. return $this->_cachedId;
  72. }
  73. }