ConnectionBase.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. return $this->readResponse($command);
  34. }
  35. protected function onCommunicationException($message, $code = null) {
  36. Utils::onCommunicationException(
  37. new CommunicationException($this, $message, $code)
  38. );
  39. }
  40. public function getResource() {
  41. if (!$this->isConnected()) {
  42. $this->connect();
  43. }
  44. return $this->_resource;
  45. }
  46. public function getParameters() {
  47. return $this->_params;
  48. }
  49. public function __toString() {
  50. if (!isset($this->_cachedId)) {
  51. $this->_cachedId = "{$this->_params->host}:{$this->_params->port}";
  52. }
  53. return $this->_cachedId;
  54. }
  55. }