| 1 | # $Id: /mirror/gungho/lib/Gungho/Component/Cache.pm 31133 2007-11-27T01:57:33.833442Z lestrrat $ | ||
| 2 | # | ||
| 3 | # Copyright (c) 2007 Daisuke Maki <daisuke@endeworks.jp> | ||
| 4 | # All rights reserved. | ||
| 5 | |||
| 6 | package Gungho::Component::Cache; | ||
| 7 | use strict; | ||
| 8 | use warnings; | ||
| 9 | use base qw(Gungho::Component); | ||
| 10 | |||
| 11 | __PACKAGE__->mk_classdata( '_backends' => {} ); | ||
| 12 | __PACKAGE__->mk_classdata( 'default_backend' ); | ||
| 13 | |||
| 14 | sub setup | ||
| 15 | { | ||
| 16 | my $c = shift; | ||
| 17 | $c->next::method(@_); | ||
| 18 | $c->setup_cache_backends(); | ||
| 19 | } | ||
| 20 | |||
| 21 | sub setup_cache_backends | ||
| 22 | { | ||
| 23 | my $c = shift; | ||
| 24 | my $config = $c->config->{cache}; | ||
| 25 | |||
| 26 | if ($config->{default_backend}) { | ||
| 27 | $c->default_backend($config->{default_backend}); | ||
| 28 | } | ||
| 29 | |||
| 30 | my $backends = $c->_backends(); | ||
| 31 | while (my($name, $config) = each %{ $config->{backends} } ) { | ||
| 32 | my $class = delete($config->{class}) || delete($config->{module}); | ||
| 33 | die "No class specified for cache backend" unless $class; | ||
| 34 | my $pkg = $c->load_gungho_module( $class, __PACKAGE__); | ||
| 35 | |||
| 36 | $backends->{$name} = $pkg->new(%$config); | ||
| 37 | } | ||
| 38 | } | ||
| 39 | |||
| 40 | sub cache | ||
| 41 | { | ||
| 42 | my ($c, $name) = @_; | ||
| 43 | my $cache; | ||
| 44 | |||
| 45 | if ($name) { | ||
| 46 | $cache = $c->_backends->{$name} ; | ||
| 47 | if (! $cache) { | ||
| 48 | Carp::croak("No cache backend by name $name specified"); | ||
| 49 | } | ||
| 50 | } else { | ||
| 51 | if ($c->default_backend) { | ||
| 52 | $cache = $c->_backends->{$c->default_backend}; | ||
| 53 | } | ||
| 54 | if (! $cache) { | ||
| 55 | Carp::croak("No default backend specified"); | ||
| 56 | } | ||
| 57 | } | ||
| 58 | return $cache; | ||
| 59 | } | ||
| 60 | |||
| 61 | 1; | ||
| 62 | |||
| 63 | __END__ |