NAME

Class::Prototyped - Fast prototype-based OO programming in Perl

SYNOPSIS

use blib;
use strict;
use Class::Prototyped ':EZACCESS';

$, = ' '; $\ = "\n";

my $p = Class::Prototyped->new(
  field1 => 123,
  sub1   => sub { print "this is sub1 in p" },
  sub2   => sub { print "this is sub2 in p" }
);

$p->sub1;
print $p->field1;
$p->field1('something new');
print $p->field1;

my $p2 = Class::Prototyped::new(
  'parent*' => $p,
  field2    => 234,
  sub2      => sub { print "this is sub2 in p2" }
);

$p2->sub1;
$p2->sub2;
print ref($p2), $p2->field1, $p2->field2;
$p2->field1('and now for something different');
print ref($p2), $p2->field1;

$p2->addSlots( sub1 => sub { print "this is sub1 in p2" } );
$p2->sub1;

print ref($p2), "has slots", $p2->reflect->slotNames;

$p2->reflect->include( 'xx.pl' ); # includes xx.pl in $p2's package
print ref($p2), "has slots", $p2->reflect->slotNames;
$p2->aa();    # calls aa from included file xx.pl

$p2->deleteSlots('sub1');
$p2->sub1;

DESCRIPTION

This package provides for efficient and simple prototype-based programming in Perl. You can provide different subroutines for each object, and also have objects inherit their behavior and state from another object.

The structure of an object is inspected and modified through mirrors, which are created by calling reflect on an object or class that inherits from Class::Prototyped.

CONCEPTS

Slots

Class::Prototyped borrows very strongly from the language Self (see http://www.sun.com/research/self for more information). The core concept in Self is the concept of a slot. Think of slots as being entries in a hash, except that instead of just pointing to data, they can point to objects, code, or parent objects.

So what happens when you send a message to an object (that is to say, you make a method call on the object)? First, Perl looks for that slot in the object. If it can't find that slot in the object, it searches for that slot in one of the object's parents (which we'll come back to later). Once it finds the slot, if the slot is a block of code, it evaluates the code and returns the return value. If the slot references data, it returns that data. If you assign to a data slot (through a method call), it modifies the data.

Distinguishing data slots and method slots is easy - the latter are references to code blocks, the former are not. Distinguishing parent slots is not so easy, so instead a simple naming convention is used. If the name of the slot ends in an asterisk, the slot is a parent slot. If you have programmed in Self, this naming convention will feel very familiar.

Reflecting

In Self, to examine the structure of an object, you use a mirror. Just like using his shield as a mirror enabled Perseus to slay Medusa, holding up a mirror enables us to look upon an object's structure without name space collisions.

Because the mirror methods super, addSlot(s), deleteSlot(s), and getSlot(s) are called frequently on objects, there is an import keyword :EZACCESS that adds methods to the object space that call the appropriate reflected variants.

Classes vs. Objects

In Self, everything is an object and there are no classes at all. Perl, for better or worse, has a class system based on packages. We decided that it would be better not to throw out the conventional way of structuring inheritance hierarchies, so in Class::Prototyped, classes are first-class objects.

However, objects are not first-class classes. To understand this dichotomy, we need to understand that there is a difference between the way "classes" and the way "objects" are expected to behave. The central difference is that "classes" are expected to persist whether or not that are any references to them. If you create a class, the class exists whether or not it appears in anyone's @ISA and whether or not there are any objects in it. Once a class is created, it persists until the program terminates.

Objects, on the other hand, should follow the normal behaviors of reference-counted destruction - once the number of references to them drops to zero, they should miraculously disappear - the memory they used needs to be returned to Perl, their DESTROY methods need to be called, and so forth.

Since we don't require this behavior of classes, it's easy to have a way to get from a package name to an object - we simply stash the object that implements the class in $Class::Prototyped::Mirror::objects{$package}. But we can't do this for objects, because if we do the object will persist forever, for that reference will always exist.

Weak references would solve this problem, but weak references are still considered alpha and unsupported ($WeakRef::VERSION = 0.01), and we didn't want to make Class::Prototyped dependent on such a module.

So instead, we differentiate between classes and objects. In a nutshell, if an object has an explicit package name (i.e. something other than the auto-generated one), it is considered to be a class, which means it persists even if the object goes out of scope.

To create such an object, use the newPackage method, like so:

{
  my $object = Class::Prototyped->newPackage('MyClass',
      field => 1,
      double => sub {$_[0]->field*2}
    );
}

print MyClass->double,"\n";

Notice that the class persists even though $object goes out of scope. If $object were created with an auto-generated package, that would not be true. Thus, for instance, it would be a very, very, very bad idea to add the package name of an object as a parent to another object - when the first object goes out of scope, the package will disappear, but the second object will still have it in it's @ISA.

Except for the crucial difference that you should never, ever, ever make use of the package name for an object for any purpose other than printing it to the screen, objects and classes are simply different ways of inspecting the same entity.

To go from an object to a package, you can do one of the following:

$package = ref($object);
$package = $object->reflect->package;

The two are equivalent, although the first is much faster. Just remember, if $object is in an auto-generated package, don't do anything with that $package but print it.

To go from a package to an object, you do this:

$object = $package->reflect->object;

Note that $package is simple the name of the package - the following code works perfectly:

$object = MyClass->reflect->object;

But keep in mind that $package has to be a class, not an auto-generated package name for an object.

Class Manipulation

This lets us have tons of fun manipulating classes at run time. For instance, if you wanted to add, at run-time, a new method to the MyClass class? Assuming that the MyClass inherits from Class::Prototyped or that you have specified :REFLECT on the use Class::Prototyped call, you simply write:

MyClass->reflect->addSlot(myMethod => sub {print "Hi there\n"});

Just as you can clone objects, you can clone classes that are derived from Class::Prototyped. This creates a new object that has a copy of all of the slots that were defined in the class. Note that if you simply want to be able to use Data::Dumper on a class, calling MyClass->reflect->object is the preferred approach. Or simply use the dump mirror method.

The code that implements reflection on classes automatically creates slot names for package methods as well as parent slots for the entries in @ISA. This means that you can code classes like you normally do - by doing the inheritance in @ISA and writing package methods.

If you manually add subroutines to a package at run-time and want the slot information updated properly (although this really should be done via the addSlots mechanism, but maybe you're twisted:), you should do something like:

$package->reflect->_vivified_methods(0);
$package->reflect->_autovivify_methods;

Parent Slots

Adding parent slots is no different than adding normal slots - the naming scheme takes care of differentiating.

Thus, to add $foo as a parent to $bar, you write:

$bar->reflect->addSlot('fooParent*' => $foo);

However, keeping with our concept of classes as first class objects, you can also write the following:

$bar->reflect->addSlot('mixIn*' => 'MyMix::Class');

It will automatically require the module in the namespace of $bar and make the module a parent of the object. This can load a module from disk if needed.

If you're lazy, you can add parents without names like so:

$bar->reflect->addSlot('*' => $foo);

The slots will be automatically named for the package passed in - in the case of Class::Prototyped objects, the package is of the form PKG0x12345678. In the following example, the parent slot will be named MyMix::Class*.

$bar->reflect->addSlot('*' => 'MyMix::Class');

Parent slots are added to the inheritance hierarchy in the order that they were added. Thus, in the following code, slots that don't exist in $foo are looked up in $fred (and all of its parent slots) before being looked up in $jill.

$foo->reflect->addSlots('fred*' => $fred, 'jill*' => $jill);

Note that addSlot and addSlots are identical - the variants exist only because it looks ugly to add a single slot by calling addSlots.

If you need to reorder the parent slots on an object, look at promoteParents. That said, there's a shortcut for prepending a slot to the inheritance hierarchy. Simply add a second asterisk to the end of the slotname when calling addSlots. The second asterisk will be automatically stripped from the end of the slotname before the slot is prepended to the hierarchy.

Finally, in keeping with our principle that classes are first-class object, the inheritance hierarchy of classes can be modified through addSlots and deleteSlots, just like it can for objects. The following code adds the $foo object as a parent of the MyClass class, prepending it to the inheritance hierarchy:

MyClass->reflect->addSlots('foo**' => $foo);

Operator Overloading

In Class::Prototyped, you do operator overloading by adding slots with the right name. First, when you do the use on Class::Prototyped, make sure to pass in :OVERLOAD so that the operator overloading support is enabled.

Then simply pass the desired methods in as part of the object creation like so:

$foo = Class::Prototyped->new(
    value => 3,
    '""'  => sub { my $self = shift; $self->value( $self->value + 1 ) },
);

This creates an object that increments its field value by one and returns that incremented value whenever it is stringified.

Since there is no way to find out which operators are overloaded, if you add overloading to a class through the use of use overload, that behavior will not show up as slots when reflecting on the class. However, addSlots does work for adding operator overloading to classes. Thus, the following code does what is expected:

package MyClass;
@MyClass::ISA = qw(Class::Prototyped);

MyClass->reflect->addSlots(
    '""' => sub { my $self = shift; $self->value( $self->value + 1 ) },
);

package main;

$foo = MyClass->new( value => 2 );
print $foo, "\n";

Provided, of course, that MyClass finds its way into $foo as a parent during $foo's instantiation.

Object Class

The special parent slot class* is used to indicate object class. When you create Class::Prototyped objects, the class* slot is not set. If, however, you create objects by calling new on a class that inherits from Class::Prototyped, the slot class* points to the package name.

The value of this slot can be returned quite easily like so:

$foo->reflect->class;

Class is set when new is called on a package or object that has a named package.

Calling Inherited Methods

Methods (and fields) inherited from prototypes or classes are not generally available using the usual Perl $self->SUPER::something() mechanism.

The reason for this is that SUPER::something is hardcoded to the package in which the subroutine (anonymous or otherwise) was defined. For the vast majority of programs, this will be main::, and thus <SUPER::> will look in @main::ISA (not a very useful place to look).

To get around this, a very clever wrapper can be automatically placed around your subroutine that will automatically stash away the package to which the subroutine is attached. From within the subroutine, you can use the super mirror method to make an inherited call. However, because we'd rather not write code that attempts to guess as to whether or not the subroutine uses the super construct, you have to tell addSlots that the subroutine needs to have this wrapper placed around it. To do this, simply append an "!" to the end of the slot name. This "!" does not belong to the slot name - it is simply an indicator to addSlots that the subroutine needs to have super support enabled.

For instance, the following code will work:

use Class::Prototyped;

my $p1 = Class::Prototyped->new(
    method => sub { print "this is method in p1\n" },
);

my $p2 = Class::Prototyped->new(
    '*'       => $p1,
    'method!' => sub {
        print "this is method in p2 calling method in p1: ";
        $_[0]->reflect->super('method');
    },
);

To make things easier, if you specify :EZACCESS during the import, super can be called directly on an object rather than through its mirror.

The other thing of which you need to be aware is copying methods from one object to another. The proper way to do this is like so:

$foo->reflect->addSlot($bar->reflect->getSlot('method'));

When the getSlot method is called in an array context, it returns both the slot name and the slot. If it notices that the slot in question is a method and that it is a method wrapped so that inherited methods can be called, it will automatically append an "!" to the returned slot name, thus making it safe for use in addSlot.

Finally, to help protect the code, the super method is smart enough to determine whether it was called within a wrapped subroutine. If it wasn't, it croaks, thus indicating that the method should have had an "!" appended to the slot name when it was added. If you wish to disable this checking (which will improve the performance of your code, of course, but could result in very hard to trace bugs if you haven't been careful), see the import option :SUPER_FAST.

IMPORT OPTIONS

:OVERLOAD

This configures the support in Class::Prototyped for using operator overloading.

:REFLECT

This defines UNIVERSAL::reflect to return a mirror for any class. With a mirror, you can manipulate the class, adding or deleting methods, changing its inheritance hierarchy, etc.

:EZACCESS

This adds the methods addSlot, addSlots, deleteSlot, deleteSlots, getSlot, getSlots, and super to Class::Prototyped.

This lets you write:

$foo->addSlot(myMethod => sub {print "Hi there\n"});

instead of having to write:

$foo->reflect->addSlot(myMethod => sub {print "Hi there\n"});

The other methods in Class::Prototyped::Mirror should be accessed through a mirror (otherwise you'll end up with way too much name space pollution for your objects:).

:SUPER_FAST

Switches over to the fast version of super that doesn't check to see whether methods that use inherited calls had "!" appended to their slot names.

:NEW_MAIN

Creates a new function in main:: that creates new Class::Prototyped objects. Thus, you can write code like:

use Class::Prototyped qw(:NEW_MAIN :EZACCESS);

my $foo = new(say_hi => sub {print "Hi!\n";});
$foo->say_hi;
:TIED_INTERFACE

This allows you to specify the sort of tied interface you wish to offer when code attempts to access a Class::Prototyped object as a hash reference. This option expects that the second parameter will specify either the package name or an alias. The currently known aliases are:

default

This specifies Class::Prototyped::Tied::Default as the tie class. The default behavior is to allow access to existing fields, but attempts to create fields, access methods, or delete slots will croak.

autovivify

This specifies Class::Prototyped::Tied::AutoVivify as the tie class. The behavior of this package allows access to existing fields, will automatically create field slots if they don't exist, and will allow deletion of field slots. Attempts to access or delete method or parent slots will croak.

Class::Prototyped Methods

new() - Construct a new Class::Prototyped object.

A new object is created. If this is called on a class that inherits from Class::Prototyped, and class* is not being passed as a slot in the argument list, the slot class* will be the first element in the inheritance list.

The passed arguments are handed off to addSlots.

For instance, the following will define a new Class::Prototyped object with two method slots and one field slot:

my $foo = Class::Prototyped->new(
    field1 => 123,
    sub1   => sub { print "this is sub1 in foo" },
    sub2   => sub { print "this is sub2 in foo" },
);

The following will create a new MyClass object with one field slot and with the parent object $bar at the beginning of the inheritance hierarchy (just before class*, which points to MyClass):

my $foo = MyClass->new(
    field1  => 123,
    'bar**' => $bar,
);

newPackage() - Construct a new Class::Prototyped object in a specific package.

Just like new, but instead of creating the new object with an arbitrary package name (actually, not entirely arbitrary - it's generally based on the hash memory address), the first argument is used as the name of the package.

If the package name is already in use, this method will croak.

clone() - Duplicate me

Duplicates an existing object or class. and allows you to add or override slots. The slot definition is the same as in new().

my $p2 = $p1->clone(
    sub1 => sub { print "this is sub1 in p2" },
);

It calls new on the object to create the new object, so if new has been overriden, the overriden new will be called.

reflect() - Return a mirror for the object or class

The structure of an object is modified by using a mirror. This is the equivalent of calling:

Class::Prototyped::Mirror->new($foo);

destroy() - The destroy method for an object

You should never need to call this method. However, you may want to override it. Because we had to directly specify DESTROY for every object in order to allow safe destruction during global destruction time when objects may have already destroyed packages in their @ISA, we had to hook DESTROY for every object. To allow the destroy behavior to be overridden, users should specify a destroy method for their objects (by adding the slot), which will automatically be called by the Class::Prototyped::DESTROY method after the @ISA has been cleaned up.

This method should be defined to allow inherited method calls (i.e. should use 'destroy!' to define the method) and should call $self->reflect->super('destroy'); at some point in the code.

Here is a quick overview of the default destruction behavior for objects:

  • Class::Prototyped::DESTROY is called because it is linked into the package for all objects at instantiation time

  • All no longer existent entries are stripped from @ISA

  • The inheritance hierarchy is searched for a DESTROY method that is not Class::Prototyped::DESTROY. This DESTROY method is stashed away for a later call.

  • The inheritance hierarchy is searched for a destroy method and it is called. Note that the Class::Prototyped::destroy method, which will either be called directly because it shows up in the inheritance hierarchy or will be called indirectly through calls to $self->reflect->super('destroy');, will delete all non-parent slots from the object. It leaves parent slots alone because the destructors for the parent slots should not be called until such time as the destruction of the object in question is complete (otherwise inherited destructors might still be executing, even though the object to which they belong has already been destroyed). This means that the destructors for objects referenced in non-parent slots may be called, temporarily interrupting the execution sequence in Class::Prototyped::destroy.

  • The previously stashed DESTROY method is called.

  • The parent slots for the object are finally removed, thus enabling the destructors for any objects referenced in those parent slots to run.

  • Final Class::Prototyped specific cleanup is run.

super() - Call a method defined in a parent

If you use the :EZACCESS import flag, you will have super defined for use to call inherited methods (see Calling Inherited Methods above).

Class::Prototyped::Mirror Methods

These are the methods you can call on the mirror returned from a reflect call. If you specify :REFLECT in the use Class::Prototyped line, addSlot, addSlots, deleteSlot, and deleteSlots will be callable on Class::Prototyped objects as well.

autoloadCall()

If you add an AUTOLOAD slot to an object, you will need to get the name of the subroutine being called. autoloadCall() returns the name of the subroutine, with the package name stripped off.

package() - Returns the name of the package for the object

object() - Returns the object itself

class() - Returns the class* slot for the underlying object

dump() - Returns a Data::Dumper string representing the object

addSlot() - An alias for addSlots

addSlots() - Add or override slot definitions

Allows you to add or override slot definitions in the receiver.

$p->reflect->addSlots(
    fred        => 'this is fred',
    doSomething => sub { print 'doing something with ' . $_[1] },
);
$p->doSomething( $p->fred );

deleteSlot() - An alias for deleteSlots

deleteSlots() - Delete one or more of the receiver's slots by name

This will let you delete existing slots in the receiver. If those slots were defined earlier in the prototype chain, those earlier definitions will now be available.

my $p1 = Class::Prototyped->new(
    field1 => 123,
    sub1   => sub { print "this is sub1 in p1" },
    sub2   => sub { print "this is sub2 in p1" }
);
my $p2 = Class::Prototyped->new(
    'parent*' => $p1,
    sub1      => sub { print "this is sub1 in p2" },
);
$p2->sub1;    # calls $p2.sub1
$p2->reflect->deleteSlots('sub1');
$p2->sub1;    # calls $p1.sub1
$p2->reflect->deleteSlots('sub1');
$p2->sub1;    # still calls $p1.sub1

super() - Call a method defined in a parent

slotNames() - Returns a list of all the slot names

This is passed an optional type parameter. If specified, it should be one of 'FIELD', 'METHOD', or 'PARENT'. For instance, the following will print out a list of all slots of an object:

print join(', ', $obj->reflect->slotNames)."\n";

The following would print out a list of all field slots:

print join(', ', $obj->reflect->slotNames('FIELD')."\n";

The parent slot names are returned in the same order for which inheritance is done.

slotType() - Given a slot name, determines the type

This returns 'FIELD', 'METHOD', or 'PARENT'. It croaks if the slot is not defined for that object.

parents() - Returns a list of all parents

Returns a list of all parent object (or package names) for this object.

allParents() - Returns a list of all parents in the hierarchy

Returns a list of all parent objects (or package names) in the object's hierarchy.

withAllParents() - Same as above, but includes self in the list

allSlotNames() - Returns a list of all slot names defined for the entire inheritance hierarchy

Note that this will return duplicate slot names if inherited slots are obscured.

getSlot() - Returns a list of all the slots

getSlots() - Returns a list of all the slots

This returns a list of slotnames and their values ready for sending to addSlots. It takes the same optional parameter passed to slotNames.

For instance, to add all of the field slots in $bar to $foo:

$foo->reflect->addSlots($bar->reflect->getSlots('FIELD'));

promoteParents() - This changes the ordering of the parent slots

This expects a list of parent slot names. There should be no duplicates and all of the parent slot names should be already existing parent slots on the object. These parent slots will be moved forward in the hierarchy in the order that they are passed. Unspecified parent slots will retain their current positions relative to other unspecified parent slots, but as a group they will be moved to the end of the hierarchy.

wrap()

unwrap()

delegate()

delegate name => slot name can be string, regex, or array of same. slot can be slot name, or object, or 2-element array with slot name or object and method name. You can delegate to a parent.

include() - include a package or external file

You can require an arbitrary file in the namespace of an object or class without adding to the parents using include() :

$foo->include( 'xx.pl' );

will include whatever is in xx.pl. Likewise for modules:

$foo->include( 'MyModule' );

will search along your @INC path for MyModule.pm and include it.

You can specify a second parameter that will be the name of a subroutine that you can use in your included code to refer to the object into which the code is being included (as long as you don't change packages in the included code). The subroutine will be removed after the include, so don't call it from any subroutines defined in the included code.

If you have the following in 'File.pl':

sub b {'xxx.b'}

sub c { return thisObject(); }    # DON'T DO THIS!

thisObject()->reflect->addSlots(
    'parent*' => 'A',
    d         => 'added.d',
    e         => sub {'xxx.e'},
);

And you include it using:

$mirror->include('File.pl', 'thisObject');

Then the addSlots will work fine, but if sub c is called, it won't find thisObject().

AUTHOR

Written by Ned Konz, perl@bike-nomad.com and Toby Everett, teverett@alascom.att.com or toby@everettak.org. 5.005_03 porting by chromatic.

Toby Everett is currently maintaining the package.

LICENSE

Copyright (c) 2001, 2002 Ned Konz and Toby Everett. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

SEE ALSO

Class::SelfMethods

Class::Object

Class::Classless