OSDN Git Service

Plugin::KeyValueStore: add cache()
authorhylom <hylom@users.sourceforge.jp>
Mon, 27 Feb 2017 12:00:11 +0000 (21:00 +0900)
committerhylom <hylom@users.sourceforge.jp>
Mon, 27 Feb 2017 12:00:11 +0000 (21:00 +0900)
src/newslash_web/lib/Newslash/Plugin/KeyValueStore.pm

index c9bd80b..abc5579 100644 (file)
@@ -12,6 +12,26 @@ sub _connect {
     return $r;
 }
 
+sub cache {
+    my $self = shift;
+    my $key = shift;
+    my $expire = shift;
+    my $func_ref = shift;
+    my @args = @_;
+
+    my $value = $self->get($key);
+
+    if ($value) {
+        # cache hit!
+        return $value;
+    }
+
+    # cache unhit, then execute function and cache result
+    $value = $func_ref->(@args);
+    $self->set($key, $value, $expire);
+    return $value;
+}
+
 sub hset {
     my ($self, $key, $field, $value) = @_;
     my $r = $self->_connect;