Warrick said:
Hi All,
I'm writing a parser for a layer 4 device (Load Ballancer), and am
trying my hand at OO .. with not much success so far.
The piece that I'm getting stuck on is association and\or adding an
array of other objects as a propery to one object.
For eaxmple: I have a virtual IP address that load ballances a group of
real server. I would like to have three types of objects
1. VirtualIP object
2. Real server Group Object
3. Real Server Object
So you would have multiple real server objects associated with one Real
Server Group object, and then you woudl have multiple group objects
associated with a virtual ip object.
Could someone please push me in the right direction here?
THanks
Warrick
It all depends on what other information you need to store. If the list
of 'sub-objects' is all you need, simply make sure each is a blessed
array ref, eg:
==== PSEUDO CODE START
package RealServer;
....
sub new {
my $class = shift;
return bless(WHATEVER, # Depends on what you need
(ref($class) or $class or __PACKAGE__);
}
package RealServerGroup;
....
sub new {
my $class = shift;
return bless([], (ref($class) or $class or
__PACKAGE__)->_init(@_);
}
sub _init {
my $self = shift;
for my $thing (whatever) {
push @$self, RealServer->new(...);
}
}
1;
package VirtualIP;
....
sub new {
my $class = shift;
return bless([], (ref($class) or $class or
__PACKAGE__)->_init(@_);
}
sub _init {
my $self = shift;
for my $thing (whatever) {
push @$self, RealServerGroup->new(...);
}
}
1;
==== PSEUDO CODE END
Of course, if you want to store more than just the sub objects, you use
a blessed hashref, eg:
==== START MORE PSEUDO CODE
package VirtualIP;
....
sub new {
my $class = shift;
return bless({}, (ref($class) or $class or
__PACKAGE__)->_init(@_);
}
sub _init {
my $self = shift;
for my $thing (whatever) {
$self->{RSG}->{$thing} = RealServerGroup->new(...);
# OR
push @{$self->{RSG}}, RealServerGroup->new(...);
}
}
1;
==== END PSEUDO CODE
You _could_ still get away with it using a blessed scalar and
class-variables, but then every single RealServerGroup you instantiate
would have the same list of RealServers (unless you get really tricky
and have the class variable as a hash indexed on each instantiated
object's string-ified value - eg RealServer=SCALAR(0x812f36c). Phew! Too
many choices

).
All you've got to remember is that a perl5 object is just a blessed
'thing' (where thing is a reference), which means you can use the
'thing' as normal, as well as using it to call functions on itself. If
the thing is a hashref, store data in it as hash key/values. If the
thing is an arrayref, store data in it by index etc etc.
Of course you don't need to fill in the array/hash on object creation -
you can have accessors/mutators that let you do it later (or you can be
messy and access the hash keys/array indices directly - this is one
thing that perl5 is badly missing when it comes to objects - data hiding)
MB