From ac380c263416a2e7bb8a13dc15ca41bbb6609610 Mon Sep 17 00:00:00 2001 From: Dave Marshall Date: Wed, 3 Jul 2013 10:27:06 +0100 Subject: [PATCH] Provide doctrine cache based storage --- composer.json | 5 +- src/Stiphle/Storage/DoctrineCache.php | 76 +++++++++++++++++++++++++++ 2 files changed, 80 insertions(+), 1 deletion(-) create mode 100644 src/Stiphle/Storage/DoctrineCache.php diff --git a/composer.json b/composer.json index 4b29a14..f8d4191 100644 --- a/composer.json +++ b/composer.json @@ -12,7 +12,10 @@ }], "require": { - "php": ">=5.3.1", + "php": ">=5.3.1" + }, + + "suggest": { "doctrine/cache": "~1.0" }, diff --git a/src/Stiphle/Storage/DoctrineCache.php b/src/Stiphle/Storage/DoctrineCache.php new file mode 100644 index 0000000..93da512 --- /dev/null +++ b/src/Stiphle/Storage/DoctrineCache.php @@ -0,0 +1,76 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +class DoctrineCache implements StorageInterface +{ + protected $lockWaitTimeout = 1000; + protected $lockWaitInterval = 100; + + public function __construct(Cache $cache, $lockWaitTimeout = 1000, $lockWaitInterval = 100) + { + $this->cache = $cache; + $this->lockWaitTimeout = $lockWaitTimeout; + $this->lockWaitInterval = $lockWaitInterval; + } + + public function setLockWaitTimeout($milliseconds) + { + $this->lockWaitTimeout = $milliseconds; + return; + } + + public function setSleep($microseconds) + { + $this->sleep = $microseconds; + return; + } + + public function lock($key) + { + $key = $key . "::LOCK"; + $start = microtime(true); + while ($this->cache->contains($key)) { + $passed = (microtime(true) - $start) * 1000; + if ($passed > $this->lockWaitTimeout) { + throw new LockWaitTimeoutException(); + } + usleep($this->sleep); + } + $this->cache->save($key, true); + + return; + } + + public function unlock($key) + { + $key = $key . "::LOCK"; + $this->cache->delete($key); + } + + public function get($key) + { + return $this->cache->fetch($key); + } + + public function set($key, $value) + { + $this->cache->save($key, $value); + return; + } + +} + + +