Mojo::Cache - Naive In-Memory Cache


Mojolicious documentation Contained in the Mojolicious distribution.

Index


Code Index:

NAME

Top

Mojo::Cache - Naive In-Memory Cache

SYNOPSIS

Top

  use Mojo::Cache;

  my $cache = Mojo::Cache->new(max_keys => 50);
  $cache->set(foo => 'bar');
  my $foo = $cache->get('foo');

DESCRIPTION

Top

Mojo::Cache is a naive in-memory cache with size limits.

Note that this module is EXPERIMENTAL and might change without warning!

ATTRIBUTES

Top

Mojo::Cache implements the following attributes.

max_keys

  my $max_keys = $cache->max_keys;
  $cache       = $cache->max_keys(50);

Maximum number of cache keys, defaults to 100.

METHODS

Top

Mojo::Cache inherits all methods from Mojo::Base and implements the following new ones.

get

  my $value = $cache->get('foo');

Get cached value.

set

  $cache = $cache->set(foo => 'bar');

Set cached value.

SEE ALSO

Top

Mojolicious, Mojolicious::Guides, http://mojolicio.us.


Mojolicious documentation Contained in the Mojolicious distribution.

package Mojo::Cache;
use Mojo::Base -base;

has 'max_keys' => 100;

# "If at first you don't succeed, give up."
sub get { (shift->{_cache} || {})->{shift()} }

# "Maybe I should hook up with you guys.
#  After all, how long do any of us have to live?
#  Well, if you like the ribwich, not very.
#  *holds up ribwich box with Krusty saying 'WILL CAUSE EARLY DEATH'*
#  D'oh!"
sub set {
  my ($self, $key, $value) = @_;

  # Cache with size limit
  my $keys  = $self->max_keys;
  my $cache = $self->{_cache} ||= {};
  my $stack = $self->{_stack} ||= [];
  delete $cache->{shift @$stack} while @$stack >= $keys;
  push @$stack, $key;
  $cache->{$key} = $value;

  $self;
}

1;
__END__