Search code examples
perloopobjectobject-composition

Perl/OOP: How to create object of "Class B" in constructor of "Class A"


I have Class A with following constructor:

sub new {
    my ($class, %args) = @_;

    return bless(\%args, $class);
}

I have another class, LWP::UserAgent, which I want to use in my Class A. I could solve the problem by doing this:

ua = LWP::UserAgent->new;

sub new {
    my ($class, %args) = @_;

    return bless(\%args, $class);
}

But in this case I will have 1 object of UserAgent, but I want a unique object for each instance of my Class A.


Solution

  • Then you need to construct that object as an attribute

    use LWP::UserAgent;
    
    sub new {
        my ($class, %args) = @_;
    
        return bless { %args, lwp => LWP::UserAgent->new }, $class;
    }
    

    and now every object of class A will have for attribute lwp its own LWP::UserAgent object.

    I would of course expect that in reality this is written out nicely with all requisite error checking.


    And I guess better call the attribute ua (instead of lwp above), for User-Agent.