Skip to content

Instantly share code, notes, and snippets.

@saltandvinegarcrisps
Last active October 25, 2016 16:14
Show Gist options
  • Save saltandvinegarcrisps/3dfcc405d59e0face5c7 to your computer and use it in GitHub Desktop.
Save saltandvinegarcrisps/3dfcc405d59e0face5c7 to your computer and use it in GitHub Desktop.
<?php
class MemcacheCollection {
protected function getIndexes() {
$result = $this->instance->get('collection_indexes');
return json_decode($result);
}
protected function updateIndexes(array $indexes) {
$value = json_encode($indexes);
$this->instance->set('collection_indexes', $value);
}
protected function getFirstIndex() {
$indexes = $this->getIndexes();
return min($indexes);
}
protected function getLastIndex() {
$indexes = $this->getIndexes();
return max($indexes);
}
protected function createNextIndex() {
$indexes = $this->getIndexes();
$key = max($indexes) + 1;
$indexes[] = $key;
$this->updateIndexes($indexes);
return $key;
}
public function push($value) {
$key = $this->createNextIndex();
$this->instance->set(sprintf('collection:%d', $key), $value);
}
protected function removeIndex($key) {
$indexes = $this->getIndexes();
$index = array_search($key, $indexes);
unset($indexes[$index]);
$this->updateIndexes($indexes);
}
protected function get($key) {
$this->removeIndex($key);
$result = $this->instance->get(sprintf('collection:%d', $key));
$this->instance->delete(sprintf('collection:%d', $key));
return $result;
}
public function pop() {
$key = $this->getLastIndex();
return $this->get($key);
}
public function shift() {
$key = $this->getFirstIndex();
return $this->get($key);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment