perlmeditation
jdhedden
Inspired by the discussion of [id://508694], I have added the capability for
[mod://Object::InsideOut] objects to inherit from non-Object::InsideOut
classes. (I refer to this as <i>foreign inheritance</i> in the POD.) Thus,
using [mod://Object::InsideOut], you can now sub-class other Perl classes, and
have access to their methods from your own inside-out objects.
<readmore>
<p>
Here's a quick-and-dirty sample that illustrates <i>foreign</i> inheritance
using [mod://Object::InsideOut] v1.18:
<code>
use strict;
use warnings;
# Borg is a foreign hash-based class
package Borg; {
# A regular hash-based constructor
sub new {
return (bless({}, shift));
}
# A 'get' accessor
sub get_borg
{
my ($self, $data) = @_;
return ($self->{$data});
}
# A 'put' accessor
sub set_borg
{
my ($self, $key, $value) = @_;
$self->{$key} = $value;
}
# A class method
sub assimilate
{
return ('Resistance is futile');
}
}
# Foo is an Object::InsideOut class that inherits from class Borg
package Foo; {
use Object::InsideOut qw(Borg);
# A data field with standard 'get_/set_' accessors
my @foo :Field('Standard'=>'foo');
# Our class's 'contructor'
sub init :Init
{
my ($self, $args) = @_;
# Create a Borg object and inherit from it
my $borg = Borg->new();
$self->inherit($borg);
}
# A class method
sub comment
{
return ('I have no comment to make at this time');
}
}
package main;
# Inheritance works on class methods
print(Foo->comment(), "\n"); # Call a 'native' class method
print(Foo->assimilate(), "\n"); # Call a 'foreign' class method
my $obj = Foo->new(); # Create our object
$obj->set_foo('I like foo'); # Set data inside our object
print($obj->get_foo(), "\n"); # Get data from our object
$obj->set_borg('ID' => 'I am 5-of-7'); # Set data inside inherited object
print($obj->get_borg('ID'), "\n"); # Get data from inherited object
</code>
Other points of interest:
<ul><li>
Muliple inheritance is supported with any mix of Object::InsideOut and
<i>foreign</i> classes.
</li><li>
The encapsulation of the inherited objects is strong, meaning that only the
class where the inheritance takes place has direct access to the inherited
object.
</li><li>
<i>Disinheritance</i> is supported to remove the association with an inherited
object.
</li></ul>
Any comments or suggestions from my fellow monks would be greatly appreciated.
Enjoy.
</readmore>
<div class="pmsig"><div class="pmsig-313108">
<hr><font size="-2">Remember: There's always one more bug.</font>
</div></div>