1 package LJ
::MemCacheable
;
6 use String
::CRC32 qw
/crc32/;
9 ## Mixin class for objects to be stored in Memcache
10 ## See LJ::MemCache and LJ::User::memcache_set_u/memcache_get_u for idea
12 ## Derived classes must implement the following methods:
13 ## _memcache_id { $_[0]->userid }
14 ## _memcache_key_prefix { "user" }
15 ## _memcache_stored_props { qw/$VERSION name age caps / }
16 ## _memcache_hashref_to_object { LJ::User->new_from_row($_[0]) }
17 ## _memcache_expires { 24*3600 }
19 ## In many cases you can use aliases for subs, e.g.:
20 ## *_memcache_hashref_to_object = \&new_from_row;
26 sub _store_to_memcache
{
29 my ($version, @props) = $self->_memcache_stored_props;
31 foreach my $key (@props) {
32 push @data, $self->{$key};
34 LJ
::MemCacheProxy
::set
($self->_memcache_key, \
@data, $self->_memcache_expires);
37 sub _load_from_memcache
{
41 my $data = LJ
::MemCacheProxy
::get
($class->_memcache_key($id));
42 return unless $data && ref $data eq 'ARRAY';
44 my ($version, @props) = $class->_memcache_stored_props;
45 ## check if memcache contains data with actual version
46 return unless $data->[0]==$version;
48 foreach my $i (0..$#props) {
49 $hash{ $props[$i] } = $data->[$i+1];
51 return $class->_memcache_hashref_to_object(\
%hash);
54 ## warning: instance or class method.
55 ## $id may be absent when calling on instance.
56 sub _remove_from_memcache
{
59 LJ
::MemCacheProxy
::delete($class->_memcache_key($id));
64 my $id = shift || $class->_memcache_id;
65 my $prefix = $class->_memcache_key_prefix;
67 return [$id, "$prefix:$id"];
70 return [(crc32
($id) >> 16) & 0x7fff, "$prefix:$id"];