add files
|
1 |
package Mojo::Cache; |
2 |
use Mojo::Base -base; |
|
3 | ||
4 |
has 'max_keys' => 100; |
|
5 | ||
6 |
sub get { (shift->{cache} || {})->{shift()} } |
|
7 | ||
8 |
sub set { |
|
9 |
my ($self, $key, $value) = @_; |
|
10 | ||
11 |
my $cache = $self->{cache} ||= {}; |
|
12 |
my $queue = $self->{queue} ||= []; |
|
13 |
delete $cache->{shift @$queue} if @$queue >= $self->max_keys; |
|
14 |
push @$queue, $key unless exists $cache->{$key}; |
|
15 |
$cache->{$key} = $value; |
|
16 | ||
17 |
return $self; |
|
18 |
} |
|
19 | ||
20 |
1; |
|
21 | ||
22 |
=encoding utf8 |
|
23 | ||
24 |
=head1 NAME |
|
25 | ||
26 |
Mojo::Cache - Naive in-memory cache |
|
27 | ||
28 |
=head1 SYNOPSIS |
|
29 | ||
30 |
use Mojo::Cache; |
|
31 | ||
32 |
my $cache = Mojo::Cache->new(max_keys => 50); |
|
33 |
$cache->set(foo => 'bar'); |
|
34 |
my $foo = $cache->get('foo'); |
|
35 | ||
36 |
=head1 DESCRIPTION |
|
37 | ||
38 |
L<Mojo::Cache> is a naive in-memory cache with size limits. |
|
39 | ||
40 |
=head1 ATTRIBUTES |
|
41 | ||
42 |
L<Mojo::Cache> implements the following attributes. |
|
43 | ||
44 |
=head2 max_keys |
|
45 | ||
46 |
my $max = $cache->max_keys; |
|
47 |
$cache = $cache->max_keys(50); |
|
48 | ||
49 |
Maximum number of cache keys, defaults to C<100>. |
|
50 | ||
51 |
=head1 METHODS |
|
52 | ||
53 |
L<Mojo::Cache> inherits all methods from L<Mojo::Base> and implements the |
|
54 |
following new ones. |
|
55 | ||
56 |
=head2 get |
|
57 | ||
58 |
my $value = $cache->get('foo'); |
|
59 | ||
60 |
Get cached value. |
|
61 | ||
62 |
=head2 set |
|
63 | ||
64 |
$cache = $cache->set(foo => 'bar'); |
|
65 | ||
66 |
Set cached value. |
|
67 | ||
68 |
=head1 SEE ALSO |
|
69 | ||
70 |
L<Mojolicious>, L<Mojolicious::Guides>, L<http://mojolicio.us>. |
|
71 | ||
72 |
=cut |