| 1 | package RWDE::DB::Cachable; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | use NEXT; | ||
| 7 | |||
| 8 | use Error qw(:try); | ||
| 9 | use RWDE::Exceptions; | ||
| 10 | |||
| 11 | use RWDE::DB::MemcachedRegistry; | ||
| 12 | |||
| 13 | use vars qw($VERSION); | ||
| 14 | $VERSION = sprintf "%d", q$Revision: 508 $ =~ /(\d+)/; | ||
| 15 | |||
| 16 | ## @method protected object _fetch_by_id() | ||
| 17 | # Private routine to fetch a record by class_id | ||
| 18 | # @return the populated object | ||
| 19 | sub _fetch_by_id { | ||
| 20 | my ($self, $params) = @_; | ||
| 21 | |||
| 22 | my $id = $$params{ $self->{_id} }; | ||
| 23 | |||
| 24 | my $memh = RWDE::DB::MemcachedRegistry->get_memh({ host => $self->{_cache_host} }); | ||
| 25 | |||
| 26 | my $term = $memh->get({ key => $self->get_cache_key({ id => $id }) }); | ||
| 27 | |||
| 28 | if (not defined $term) { | ||
| 29 | $term = $self->NEXT::_fetch_by_id($params); | ||
| 30 | $memh->add({ term => $term }); | ||
| 31 | } | ||
| 32 | |||
| 33 | return $term; | ||
| 34 | } | ||
| 35 | |||
| 36 | ## @method void update_record() | ||
| 37 | # Update the record specified by the C<id> field with values | ||
| 38 | # specified in the data fields of this object. Only updates the fields | ||
| 39 | # specified -- other fields are left alone. Returns 1 on on success, or | ||
| 40 | # throws an exception on failure. | ||
| 41 | # | ||
| 42 | # Exceptions classes thrown are C<dberr> on database error or | ||
| 43 | # C<data.missing> for a missing ID. | ||
| 44 | |||
| 45 | sub update_record { | ||
| 46 | my ($self, $params) = @_; | ||
| 47 | |||
| 48 | $self->NEXT::update_record($params); | ||
| 49 | |||
| 50 | $self->delete_cache(); | ||
| 51 | |||
| 52 | return (); | ||
| 53 | } | ||
| 54 | |||
| 55 | ## @method void update_all() | ||
| 56 | # (Enter update_all info here) | ||
| 57 | sub update_all { | ||
| 58 | my ($self, $params) = @_; | ||
| 59 | |||
| 60 | $self->NEXT::update_all($params); | ||
| 61 | |||
| 62 | $self->delete_cache(); | ||
| 63 | |||
| 64 | return (); | ||
| 65 | } | ||
| 66 | |||
| 67 | ## @method void delete_cache() | ||
| 68 | # (Enter delete_cache info here) | ||
| 69 | sub delete_cache { | ||
| 70 | my ($self, $params) = @_; | ||
| 71 | |||
| 72 | my $memh = RWDE::DB::MemcachedRegistry->get_memh({ host => $self->{_cache_host} }); | ||
| 73 | |||
| 74 | $memh->delete({ term => $self }); | ||
| 75 | |||
| 76 | return (); | ||
| 77 | } | ||
| 78 | |||
| 79 | sub get_cache_key { | ||
| 80 | my ($self, $params) = @_; | ||
| 81 | |||
| 82 | if (defined $$params{id}) { | ||
| 83 | return $self->get_id_name . '::' . $$params{id}; | ||
| 84 | } | ||
| 85 | else { | ||
| 86 | return $self->get_id_name . '::' . $self->get_id; | ||
| 87 | } | ||
| 88 | } | ||
| 89 | |||
| 90 | 1; | ||
| 91 |