Class::FakeAttributes - Provide fake attributes for non-hash-based objects


  use base qw<Class::FakeAttributes Some::Other::Module>;
  sub something
    my ($self, $whatever) = @_;

    $self->set_attribute(motto => $whatever);
    my $size = $self->get_attribute('size');
    # etc


This is version 0.01. It exists for discussion. Do not rely on it. Everything is subject to change, including the module's functionality, API, name, and even its existence. Comments are welcome on the mailing list.


Most Perl classes use hash-based objects, and subclasses can easily add more attributes (instance data) with new hash keys. But some classes are not based on hashes. A subclass of such a class can use Class::FakeAttributes to add attributes (or at least to emulate doing so).

Class::FakeAttributes is a mixin class: the only sensible use is to inherit from it, and it only makes sense to do that when also inheriting from something else as well.



Use set_attribute() to set an attribute on an object. Where with a hash-based object you would have written:

  $self->{key} = $value;

instead write:

  $self->set_attribute(key => $value);


Get the value of an attribute (set by set_attribute()) with get_attribute(). Instead of this hash-based code:

  my $value = $self->{key};


  my $value = $self->get_attribute('key');


For an attribute that has a list of values, append to that list with push_attribute(). Instead of this hash-based code:

  push @{$self->{key}}, $value;


  $self->push_attribute(key => $value);

Multiple values can be pushed at once:

  $self->push_attribute(food => @fruit);


Retrieve the list of all values for a key with attribute_list. Instead of this hash-based code:

  foreach (@{$self->{key})


  foreach ($self->attribute_list('key'))


The memory used to store an object's attributes is freed in a DESTROY method provided by Class::FakeAttributes. If DESTROY doesn't get called then memory will be leaked. The best way to ensure memory gets freed up properly is to put Class::FakeAttributes at the start of the inheritance list. That is, don't do this:

  use base qw<Class::FakeAttributes Some::Other::Module>;

do this:

  use base qw<Some::Other::Module Class::FakeAttributes>;

Class::FakeAttributes uses the NEXT module to ensure that, so long as it is listed first, any DESTROY method in other superclasses will also be invoked.


Smylers <>


© Copyright Smylers 2003. All rights reserved. This module is software libre. It may be used, redistributed, or modified under the terms of the Artistic License (the unnumbered version that comes with Perl 5.6.1, among others) or the GNU General Public License version 2.