Predis.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace League\Flysystem\Cached\Storage;
  3. use Predis\Client;
  4. class Predis extends AbstractCache
  5. {
  6. /**
  7. * @var \Predis\Client Predis Client
  8. */
  9. protected $client;
  10. /**
  11. * @var string storage key
  12. */
  13. protected $key;
  14. /**
  15. * @var int|null seconds until cache expiration
  16. */
  17. protected $expire;
  18. /**
  19. * Constructor.
  20. *
  21. * @param \Predis\Client $client predis client
  22. * @param string $key storage key
  23. * @param int|null $expire seconds until cache expiration
  24. */
  25. public function __construct(Client $client = null, $key = 'flysystem', $expire = null)
  26. {
  27. $this->client = $client ?: new Client();
  28. $this->key = $key;
  29. $this->expire = $expire;
  30. }
  31. /**
  32. * {@inheritdoc}
  33. */
  34. public function load()
  35. {
  36. if (($contents = $this->executeCommand('get', [$this->key])) !== null) {
  37. $this->setFromStorage($contents);
  38. }
  39. }
  40. /**
  41. * {@inheritdoc}
  42. */
  43. public function save()
  44. {
  45. $contents = $this->getForStorage();
  46. $this->executeCommand('set', [$this->key, $contents]);
  47. if ($this->expire !== null) {
  48. $this->executeCommand('expire', [$this->key, $this->expire]);
  49. }
  50. }
  51. /**
  52. * Execute a Predis command.
  53. *
  54. * @param string $name
  55. * @param array $arguments
  56. *
  57. * @return string
  58. */
  59. protected function executeCommand($name, array $arguments)
  60. {
  61. $command = $this->client->createCommand($name, $arguments);
  62. return $this->client->executeCommand($command);
  63. }
  64. }