You cannot get to those my variables. Class variables are usually handled with some sort of package variable, like %Obj::foo_cache, by creating accessor methods that are in the same scope (think closure) that the kiddie subclasses can call, or by squirreling away references to the data inside each and every instance. Perl only objectifies methods, nothing else, so games have to be played to get class data visible to subclasses.
The way you're asking this question, I think you need to brush up on how Perl handles packages, name spaces, closures, and the like. The techniques are the same for OO and standard procedural.
Also, this isn't "has-a", this is pure "is-a". At no point do I see you trying to allocate an intermediate object, and redirecting request to it. I don't know if that matters or not. For "has-a", Foo would not have Obj as a base, but would have a reference to a Obj object and would pass foo_cache requests to it.
All that said, the easiest way is an accessor method in the Obj package, like this snippet
sub foo_cache() { \%foo_cache; }
and your Obj::Foo subclass would use stuff like
if ( exists $self->foo_cache()->{$key} ) { # cache hit
$value = $self->foo_cache()->{$key};
} else { # this means a cache miss
$value = calculate_something_worth_caching();
$self->foo_cache()->{$key} = $value; # store in cache
}
If you think you've just broken encapsulation, and you've now tightly bound the Obj::Foo subclass to the implementation details of its parent Obj class, then you understand why I wouldn't do it it this way. But if you're just learning, this should get you going. Once you've gotten a bit more experience, convert that to having a get_foo() and set_foo() in Obj foo can call and be unaware of the details of %foo_cache. I mean, caches are supposed to be transparent, right?
In a lot of cases, caching can be implemented with the Memoize module, so you might want to look at it too.
- doug
PS: Love the moose. Touch the moose. Grok the moose. |