in reply to Re: Perl OOP help for OOP newbie
in thread Perl OOP help for OOP newbie

Thanks for your reply. I don't get your comment "Instead, you probably should have an instance variable in each Account that references the User object that it is associated with." Surely, User::Account belongs to User? and I don't understand how you'd create an instance variable in each Account that references the User object - how do you do that? Presumably you are referring to the $self in "return User::Account->new($self, $account_id); ".

I'll work on your idea and see where I get.

Replies are listed 'Best First'.
Re^3: Perl OOP help for OOP newbie
by 7stud (Deacon) on Jun 02, 2011 at 02:54 UTC

    Inheritance is for "is a" relationships. For instance, a BMW "is a" SportsCar, so BMW could inherit from SportsCar. Now let's try it with your class: An Account "is a" User. That isn't true, so Account would not inherit from User.

    "Composition" is for "has a" relationships. For instance, a User "has a(n)" Account. In your case, composition would involve assigning an Account object to a User variable. If your User object uses a hash internally, then one key in the hash could be called ACCOUNTS, and its value could be a reference to an array. The array would contain various Account objects.

Re^3: Perl OOP help for OOP newbie
by NetWallah (Canon) on Jun 01, 2011 at 23:06 UTC
    If a user has multiple accounts, I'd suggest this:
    package User; sub new { my ($class, $username) = @_; my $self =(username=> $username, accounts=>{} , # No accounts for a +new user server=> {Some server connection info} ); bless $self, $class; } sub open_account { my ($self, $account_id) = @_; return $self->accounts->{$account_id} = User::Account->new($self, $ac +count_id); } # accessor for accounts.. sub get_account{ my ($self,account_id) = @_; return $self->accounts->{account_id}; }

                "XML is like violence: if it doesn't solve your problem, use more."