ConnectionBase.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. abstract class ConnectionBase implements IConnectionSingle {
  9. private $_cachedId;
  10. protected $_params, $_initCmds, $_resource;
  11. public function __construct(ConnectionParameters $parameters) {
  12. $this->_initCmds = array();
  13. $this->_params = $parameters;
  14. }
  15. public function __destruct() {
  16. $this->disconnect();
  17. }
  18. public function isConnected() {
  19. return is_resource($this->_resource);
  20. }
  21. protected abstract function createResource();
  22. public function connect() {
  23. if ($this->isConnected()) {
  24. throw new ClientException('Connection already estabilished');
  25. }
  26. $this->_resource = $this->createResource();
  27. }
  28. public function pushInitCommand(ICommand $command){
  29. $this->_initCmds[] = $command;
  30. }
  31. public function executeCommand(ICommand $command) {
  32. $this->writeCommand($command);
  33. if ($command->closesConnection()) {
  34. return $this->disconnect();
  35. }
  36. return $this->readResponse($command);
  37. }
  38. protected function onCommunicationException($message, $code = null) {
  39. Utils::onCommunicationException(
  40. new CommunicationException($this, $message, $code)
  41. );
  42. }
  43. public function getResource() {
  44. if (!$this->isConnected()) {
  45. $this->connect();
  46. }
  47. return $this->_resource;
  48. }
  49. public function getParameters() {
  50. return $this->_params;
  51. }
  52. public function __toString() {
  53. if (!isset($this->_cachedId)) {
  54. $this->_cachedId = "{$this->_params->host}:{$this->_params->port}";
  55. }
  56. return $this->_cachedId;
  57. }
  58. }