Ah, I think I see where the misunderstanding lies.
You ("you" meaning zigster) are assuming that I'm autogenerating methods based on the underlying object implementation. That's not what I'm talking about. I'm talking about generating methods based on some other standard, like so:
Note: code based on working code and Camel, but untested
And in other code...package Foo; use strict; use vars qw($AUTOLOAD %ACCESSOR_TABLE); use Carp; %ACCESSOR_TABLE = ( 'name' => '_name', 'id' => '_id_code', 'phone' => '_phonenum' ); sub DESTROY { } sub new { my $type = shift; my ($name, $id, $phone) = @_; my $self = { _data_table => { _name => $name, _id_code => $id, _phonenum => $phone, }, }; bless $self, $type; return $self; } sub AUTOLOAD { my ($sub_name) = $AUTOLOAD =~ m{.*::(.*)$}; $sub_name =~ /^get_(.*)/ or croak "Can't autoload method $AUTOLOAD +"; my $data_name = $1; defined $ACCESSOR_TABLE{$data_name} or croak "Can't autoload method $AUTOLOAD"; my $field_name = $ACCESSOR_TABLE{$data_name}; *$AUTOLOAD = sub { (ref($_[0]) && $_[0]->isa('Foo')) or croak "Accessor method '$ +sub_name' called improperly"; return $_[0]->{'_data_table'}{$field_name}; }; goto &$AUTOLOAD; }
Then, I can add accessors by merely messing with the %ACCESSOR_TABLE, and not defining more subroutines. This is particularily useful for objects which are loaded from databases-- I can add new fields to the database without doing as much recoding. If there are accessors that don't store their data in '_data_table', I can define them separately, or just add some functionality to AUTOLOAD.use Foo; my $foo = Foo->new('jenny', '24601', '408-867-5309'); my $phone = $foo->get_phone(); my $name = $foo->get_name();
These are implementation details; I just want to show that there are legitimate uses for AUTOLOAD in an object-oriented context. And once again, this illustrates the power of OO. From the perspective of the class user, it doesn't matter whether I've defined individual subroutines or if I've got them autoloaded instead. The class user doesn't need to understand "what is under the hood."
stephen
Update: Added an 'accessor exists' check.
In reply to Re: (Zigster) Re: Re: Perl and Objects, how do you resolve the two?
by stephen
in thread Perl and Objects, how do you resolve the two?
by frankus
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |