in reply to Perl and Objects, how do you resolve the two?
However, I have to vehemently disagree with the concept of using AUTOLOAD to do everything. Frankly, that's unmaintainable in the long run. (Not to mention being a little slower than previously-declared functions.) Here is a basic OO design I am currently using in a medium application and it works beautifully:
sub get_attribute_names_and_defaults { my $pkg = shift; $pkg = ref($pkg) if ref($pkg); my @result = @{"${pkg}::_ATTRIBUTES_"}; if (defined @{"${pkg}::ISA"}) { push @result, get_attribute_names_and_defaults($_) for @{"${pk +g}::ISA"}; } @result; } sub define_attributes { my $self = caller; my $pkg = ref($self) ? ref($self) : $self; my $pkg_string = "${pkg}::_ATTRIBUTES_"; if (defined @{$pkg_string}) { push @{$pkg_string}, @_; } else { @{$pkg_string} = @_; } } sub new { my $type = shift; my %args = @_; my $self = {}; bless $self, $type; my $attr_name; my $pkg = ref($self); my %defaults = Global::Generic_Object::get_attribute_names_and_def +aults($pkg ); for (keys %defaults) { $attr_name = Global::Generic_Object::_input_to_attribute(undef +, $_); unless (exists $self->{$attr_name}) { my $default_ref = ref($defaults{$_}); if ($default_ref eq 'ARRAY') { if (@{$defaults{$_}}) { $self->{$attr_name} = [ @{$defaults{$_}} ]; } else { $self->{$attr_name} = []; } } elsif ($default_ref eq 'HASH') { if (@{$defaults{$_}}) { $self->{$attr_name} = { %{$defaults{$_}} }; } else { $self->{$attr_name} = {}; } # } elsif ($default_ref eq 'SCALAR') { # $self->{$attr_name} = \$$defaults{$_}; # } elsif ($default_ref) { } else { $self->{$attr_name} = $defaults{$_}; } } } $self->_initialize(%object_hash, %args); return $self; } define_attributes(-REGISTERED_NAME => ''); sub _initialize { my $self = shift; $self->set(@_); return 1; } sub exists { my $self = shift; my @args = @_; my @return_list = (); foreach my $in (@args) { my ($obj, $data) = split (/\./, $in, 2); my $key = $self->_input_to_attribute($obj); if (exists $self->{$key}) { if ($data && ref $self->{$key} && ref($self->{$key}) =~ /: +:/) { push @return_list, $self->{$key}->exists("-$data"); } else { push @return_list, 1; } } else { push @return_list, 0; } } return @return_list == 1 ? $return_list[0] : @return_list; }
get(), set(), inc(), strcat(), and clr() all are defined in the same way. You have one function that handle attribute retrieval. That's it. Nothing more. Plus, this handles attribute inheritance as well.
Thoughts?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re (tilly) 2: Perl and Objects, how do you resolve the two?
by tilly (Archbishop) on Apr 11, 2001 at 03:35 UTC | |
by satchboost (Scribe) on Apr 11, 2001 at 19:25 UTC | |
by tilly (Archbishop) on Apr 11, 2001 at 20:26 UTC | |
by satchboost (Scribe) on Apr 11, 2001 at 22:05 UTC |