ConnectionBase.php 2.3 KB

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