framontb
framontb

Reputation: 2067

Extending a Class::Accessor in Perl to set some properties in parent class

I have a Class defined with Class::Accessor like that:

package Worker;
use Class::Accessor 'antlers';

# PROPS
has first_name      => ( is => 'rw' );
has position        => ( is => 'rw' );

# METHODS
sub print {
    my $self = shift;

    print "------------\n";
    print "Ref: ", ref $self, "\n";
    print "First Name: ", $self->first_name, "\n";

    if ($self->position) {
        print "Position: ", $self->position, "\n";
    }
}

1;

Now I want to create the Engineer class that extends Worker in such a way that property always set's to: position => 'Engineer' For example:

package Engineer;
use Class::Accessor 'antlers';
use Worker;

extends(qw/Worker/);

# METHOS

sub new {
    return bless(__PACKAGE__->SUPER::new({position => 'Engineer'}));
}

1;

But this doesn't work, because when I instantiate Engineer class like that:

use Data::Dumper;
use strict;

# Relative Path to Class libraries
use FindBin;
use lib "$FindBin::Bin/.";

use Worker;
use Engineer;

my $wor = Worker->new({first_name => 'Matt'});
my $eng = Engineer->new({first_name => 'Ray'});
$wor->print;
$eng->print;

I loose the first_name in the extended class Engineer:

------------
Ref: Worker
First Name: Matt
------------
Ref: Engineer
First Name: 
Position: Engineer

On the other hand, I'm not sure if overriding the Engineer->new() method returning a bless is a good idea...

So, How should I extend the Worker class to get an Engineer class using Class::Accessor?

Upvotes: 1

Views: 137

Answers (1)

framontb
framontb

Reputation: 2067

This new override seems to work well:

package Engineer;
use Class::Accessor 'antlers';
use Worker;
use Data::Dumper;

extends(qw/Worker/);

# METHODS

sub new {
    my($class) = shift;
    my $obj = __PACKAGE__->SUPER::new(@_);
    $obj->position('engineer');
    return bless $obj, $class;
}

Setters and getters still working for all fields and 'position' field is initialized when object is instantiated.

Upvotes: 1

Related Questions