ConnectionBase.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. namespace Predis\Network;
  3. use Predis\Utils;
  4. use Predis\ConnectionParameters;
  5. use Predis\ClientException;
  6. use Predis\CommunicationException;
  7. use Predis\Commands\ICommand;
  8. abstract class ConnectionBase implements IConnectionSingle {
  9. private $_cachedId, $_resource;
  10. protected $_params, $_initCmds;
  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 isset($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 disconnect() {
  29. unset($this->_resource);
  30. }
  31. public function pushInitCommand(ICommand $command){
  32. $this->_initCmds[] = $command;
  33. }
  34. public function executeCommand(ICommand $command) {
  35. $this->writeCommand($command);
  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 (isset($this->_resource)) {
  45. return $this->_resource;
  46. }
  47. $this->connect();
  48. return $this->_resource;
  49. }
  50. public function getParameters() {
  51. return $this->_params;
  52. }
  53. public function __toString() {
  54. if (!isset($this->_cachedId)) {
  55. $this->_cachedId = "{$this->_params->host}:{$this->_params->port}";
  56. }
  57. return $this->_cachedId;
  58. }
  59. }