NAME
Object::Proto - objects with prototype chains
SYNOPSIS
use Object::Proto;
# Define class properties (compile time)
object 'Cat', qw(name age);
# Positional constructor - fastest
my $cat = new Cat 'Whiskers', 3;
# Named pairs constructor
my $cat = new Cat name => 'Whiskers', age => 3;
# Accessors - compiled to custom ops
print $cat->name; # getter
$cat->age(4); # setter
# Package methods work normally
package Cat;
sub speak { my $self = shift; "Meow! I am " . $self->name }
package main;
print $cat->speak; # "Meow! I am Whiskers"
print $cat->isa('Cat'); # true
# Prototype chain
my $proto = $cat->prototype;
$cat->set_prototype($other);
# Mutability controls
$cat->lock; # Prevent new properties
$cat->unlock; # Allow new properties again
$cat->freeze; # Permanent immutability
$cat->is_frozen; # Check frozen state
# Delegation - methods that pass the call on to a slot's value
object 'Service',
'logger:Object:handles(info, warn)', # $svc->info(...) calls $svc->logger->info(...)
'formatter:CodeRef:handles(format)', # $svc->format(...) calls $svc->formatter->(...)
'tags:ArrayRef:handles(add_tag=>push, tag_count=>count)',
'opts:HashRef:handles(get_opt=>get, set_opt=>set)';
my $svc = new Service logger => $logger, formatter => sub { uc shift };
$svc->info('ready');
$svc->add_tag('a', 'b'); # 2
$svc->tag_count; # 2
DESCRIPTION
Object::Proto provides an alternative to bless with prototype chains. Objects are stored as arrays (not hashes) for speed, with property names mapped to slot indices at compile time.
Objects are properly blessed into their class, so isa, can, and custom package methods all work as expected.
Each property can carry a type, a default, a builder, triggers and other modifiers; classes can inherit from one another and compose roles; and a property can delegate methods to the value it holds, with handles(...) (see "Delegation (handles)"). The accessors, and the methods handles installs, are written in C.
FUNCTIONS
object $class, @properties
Define properties for a class at compile time. This assigns slot indices and installs accessor methods. Must be called before using new.
object 'Cat', qw(name age color);
This is a convenience keyword exported by use Object::Proto. It is equivalent to calling Object::Proto::define() directly.
Object::Proto::define($class, @properties)
The underlying function that object delegates to. Use this form when you need to define classes without importing the keyword, or from outside a BEGIN block:
Object::Proto::define('Cat', qw(name age color));
Property names can include type constraints, defaults, and modifiers using the colon-separated format:
object 'Person',
'name:Str:required', # Must provide name in new()
'age:Int:default(0)', # Integer with default 0
'email:Str', # Optional string
'id:Str:required:readonly', # Required, immutable after new()
'tags:ArrayRef:default([])', # Fresh empty array per object
'logger:Object:handles(info)'; # $person->info(...) calls $person->logger->info(...)
An argument in parentheses that is never closed, such as default(12, croaks with Unterminated '(' in slot spec.
Built-in Types
The following types are available with inline checks (zero overhead):
Any - accepts any value
Defined - must be defined (not undef)
Str - defined non-reference
Int - integer value
Num - numeric value
Bool - boolean (0, 1, or empty string)
ArrayRef - array reference
HashRef - hash reference
CodeRef - code reference
Object - blessed reference
Ref - any reference, blessed or not
ScalarRef - reference to a plain scalar or to another reference (what
refcallsSCALARorREF), blessed or notRegexpRef - a
qr//regular expression, whatever class it is blessed intoGlobRef - reference to a glob, blessed or not
FileHandle - an open filehandle (a glob, glob reference or IO reference that is open or tied), or an object that isa
IO::Handle. A handle that is not open is checked withisa, which costs a method resolution lookup.ClassName - the name of a loaded package: one with a defined
$VERSION, a non-empty@ISAor at least one sub. The package is looked up, never created. This costs a symbol table lookup, and a scan of the package for a sub when it has neither$VERSIONnor@ISA.PositiveInt - an Int greater than zero
NegativeInt - an Int less than zero
NonEmptyStr - a Str whose length is greater than zero
Undef - an undefined value
Modifiers
required - must be provided in new()
readonly - setter disabled after construction
default(value) - default value if not provided
lazy - value computed on first access (requires builder)
builder(method) - method name to build lazy value
clearer - install a clear_* method to reset value
clearer(name) - install clearer with custom method name
predicate - install a has_* method to check if set
predicate(name) - install predicate with custom method name
reader(name) - install a separate getter method (Java-style get_*)
writer(name) - install a separate setter method (Java-style set_*)
trigger(method) - method called when value changes
weak - weaken references stored in this slot (prevents circular refs)
arg(name) - use different name for constructor argument (init_arg)
private - the accessor and every other method generated for the attribute callable only from the package that declared it (dies elsewhere; see "Private Attributes")
handles(...) - install methods that delegate to the slot's value: methods of an Object, calls of a CodeRef, native ops of an ArrayRef or HashRef (see "Delegation (handles)")
Default values support:
default(0) # integer
default(1.5) # number
default(text) # unquoted string
default('text') # quoted string
default([]) # fresh empty array per object
default({}) # fresh empty hash per object
default(undef) # explicit undef
Lazy and Builder
Lazy slots defer computation until first access:
object 'Config',
'settings:HashRef:lazy:builder(_build_settings)';
package Config;
sub _build_settings {
my $self = shift;
return { load_from_file() }; # Only called when accessed
}
Clearer and Predicate
Install helper methods to clear and check slot values:
object 'Person',
'nickname:Str:clearer:predicate';
my $p = new Person;
$p->has_nickname; # false
$p->nickname('Bob');
$p->has_nickname; # true
$p->clear_nickname; # reset to undef
$p->has_nickname; # false
Custom method names can be specified:
object 'Config',
'cache:HashRef:clearer(invalidate):predicate(is_cached)';
$config->is_cached; # false
$config->cache({});
$config->is_cached; # true
$config->invalidate; # clear the cache
Reader and Writer
For Java-style accessors, use reader and writer to create separate getter and setter methods:
object 'Person',
'name:Str:reader(get_name):writer(set_name)';
my $p = new Person;
$p->set_name('Alice');
print $p->get_name; # "Alice"
# The default accessor still works
print $p->name; # "Alice"
Writers enforce type constraints and fire triggers just like the default accessor. Use with readonly to prevent modification after construction:
object 'Entity',
'id:Int:readonly:reader(get_id)'; # readonly, no writer needed
Weak References
Use weak to automatically weaken references stored in a slot, preventing circular reference memory leaks:
object 'TreeNode',
'value:Str',
'parent:Object:weak', # weak ref to parent
'children:ArrayRef';
my $parent = new TreeNode value => 'root';
my $child = new TreeNode value => 'leaf', parent => $parent;
push @{$parent->children}, $child;
# parent->children points to child
# child->parent points weakly to parent
# When $parent goes out of scope and has no strong refs,
# it will be garbage collected properly
Weak references are weakened:
At construction time when passed via constructor
When set via the accessor method
When set via a custom writer method
Constructor Argument Names (init_arg)
Use arg(name) to specify a different name for the constructor argument. The accessor method still uses the property name:
object 'Config',
'api_key:Str:required:arg(_api_key)';
# Constructor uses the init_arg name
my $config = new Config _api_key => 'secret123';
# Accessor uses property name
print $config->api_key; # "secret123"
This is useful for:
Providing a "private" constructor interface while keeping simple accessor names
Migrating from other object systems that use different conventions
Creating backwards-compatible APIs
Combined with other modifiers:
object 'Widget',
'id:Int:required:readonly:arg(_widget_id)',
'config:HashRef:weak:arg(_config)';
Private Attributes
Mark an attribute private to make its accessor callable only from within the class's own package. Calling it from anywhere else dies:
object 'Cat', 'name:Str', 'age:Int:private';
package Cat;
sub meow { my $self = shift; "meow, I am " . $self->age } # ok
package main;
my $cat = new Cat name => 'Whiskers', age => 3;
$cat->name; # 'Whiskers'
$cat->meow; # 'meow, I am 3' (age read from inside Cat)
$cat->age; # dies: cannot call private attribute age on Cat from main
Access is decided by the package the calling code is compiled in, not by the object's class: a method of Cat may use the accessor (getter or setter), while code in any other package - including a subclass or the caller of a Cat method - cannot. On a violation the accessor dies with:
cannot call private attribute <name> on <class> from <caller>
The check applies to every method generated for the attribute: the accessor ($obj->age, however $obj was made, Cat->new(...)->age included), its reader, writer, clearer and predicate, and the function-call form when the accessor is imported as a function (see import_accessors). A private attribute's function-style accessor is not compiled to a custom op, so that the check can run.
The attribute stays private to the package that declared it:
An inherited private attribute may be called from the parent that declared it - so the parent's methods keep working on child objects - but not from the child class or anywhere else. A child that adds
privateto an inherited attribute with+attrbecomes its owner instead.A role's private attribute may be called from the role's methods and from the class that composed the role, but not from other classes that compose the same role, from subclasses, or anywhere else.
object 'Animal', 'legs:private';
object 'Dog', extends => 'Animal';
package Animal;
sub count_legs { $_[0]->legs } # ok, also on a Dog
package Dog;
sub dog_legs { $_[0]->legs } # dies: from Dog
Setting a private attribute through the constructor's arguments is not a call to its accessor, and is allowed from anywhere:
my $cat = Cat->new(age => 3); # ok from main
Delegation (handles)
handles(...) installs methods in the class that pass the call on to the slot's value. What a method does depends on the slot's type:
object 'Service',
'logger:Object:handles(info, warn, error)', # $svc->info(@a) is $svc->logger->info(@a)
'audit:Object:handles(log_info=>info, log_error=>error)', # renamed
'storage:Object:handles(role:Storage::API)', # every method of the role
'formatter:CodeRef:handles(format)', # $svc->format(@a) is $svc->formatter->(@a)
'hook:CodeRef:handles(fire=>method)', # $svc->fire(@a) is $svc->hook->($svc, @a)
'tags:ArrayRef:handles(push_tag=>push, all_tags=>list, tag_count=>count)',
'opts:HashRef:handles(get_opt=>get, set_opt=>set, has_opt=>exists)';
my $svc = new Service logger => $logger, formatter => sub { uc shift };
$svc->info('started'); # $logger->info('started')
$svc->format('text'); # 'TEXT'
$svc->push_tag('a', 'b'); # 2
$svc->set_opt(level => 3);
$svc->get_opt('level'); # 3
Syntax
handles(ENTRY, ENTRY, ...)
where each ENTRY is one of:
name- installname, which callsnameon the delegate (or is the native opname, or calls the code)local=>remote- installlocal, which callsremoterole:Role::Name- install every method within the role (Object slots only)
White space around names, commas and => is ignored. handles(...) may come before or after the type, and a spec may have it more than once: the lists add up. Method names must be plain identifiers ([A-Za-z_]\w*), and a name may appear only once.
Which types support it
Slot type Kind handles(x) installs a method that ...
--------- ------ ---------------------------------------------
Object method calls the method x on the object in the slot
CodeRef code calls the code ref in the slot
ArrayRef native runs the array op x on the array in the slot
HashRef native runs the hash op x on the hash in the slot
handles on any other type - including an untyped slot and a type registered with register_type - croaks when the class is defined.
Object: method delegation
$obj->local(@args) calls remote(@args) on the object in the slot. The arguments are passed as they are, the caller's context (list, scalar or void) is passed through, the delegate's return value is returned, and an exception from the delegate propagates unchanged.
The delegate is found the way the slot's own accessor finds its value: the object's own slot, then its prototype chain, then, for a lazy slot, its builder or default. If there is none, the call croaks:
Cannot delegate info to logger: logger is not set
Calling a delegated method changes nothing in the object, so it works on a frozen object and on a readonly slot, and never fires the slot's trigger. A private slot's delegating methods are public: a class can keep its logger to itself and still offer log methods.
Roles: handles(role:Name)
role:Name delegates every method within the role:
the methods it
requires;the subs defined in the role's package - not ones imported into it, not constants, not names starting with
_, and not the reserved names below;the methods the role's slots give a class that composes it: the accessor, and any reader, writer, clearer and predicate - except for private slots, whose methods the delegating class could not call.
Object::Proto::role('Storage::API', 'size:Int:reader(get_size)');
Object::Proto::requires('Storage::API', 'get', 'put');
package Storage::API; sub describe { ... }
package main;
object 'Cache', 'storage:Object:handles(role:Storage::API)';
# Cache gets get, put, describe, size and get_size
The role is read when the class is defined: methods it comes to require later are not added. A role that is not defined yet is loaded, as with does. A name given explicitly in the same handles(...) wins over the same name from the role: handles(role:Storage::API, get=>fetch) delegates get to fetch. The delegating methods count as the class's own, so they satisfy a role that requires them:
object 'Cache', 'storage:Object:handles(get, put)';
Object::Proto::with('Cache', 'Storage::API'); # passes the requires check
CodeRef: calling the code
A bare name, or local=>call, calls the code with the arguments only: $obj->format(@a) is $obj->formatter->(@a). local=>method passes the object first: $obj->fire(@a) is $obj->hook->($obj, @a), where $obj is the object the method was called on, even when the code came from its prototype. Any other name after => croaks when the class is defined. Context, results and exceptions pass through as for method delegation, and the same "not set" rule applies. A value that is not a code reference (which the type allows only through a prototype of another class, or by writing into the object directly) croaks rather than being called as a sub name.
ArrayRef ops
op args returns like changes
-------- -------------- ------------------------------ ------------- -------
push 1 or more the new number of elements push yes
unshift 1 or more the new number of elements unshift yes
pop none the element removed, or undef pop yes
shift none the element removed, or undef shift yes
list none the elements; their number in @$ref
scalar context
elements (another name for list)
count none the number of elements scalar @$ref
is_empty none true when there are none !@$ref
get index the element, or undef $ref->[$i]
set index, value the value stored $ref->[$i] = $v yes
clear none the empty list; 0 in scalar @$ref = () yes
context
Indices count from the end when negative, as in perl; set past the end extends the array, and set before its start croaks as perl does.
HashRef ops
op args returns like changes
-------- -------------- ---------------------------------- --------------- -------
get 1 or more keys the value; with several keys, the $h{k}, @h{...}
values, or the last in scalar context
set key/value pairs the value; with several pairs, the $h{k} = v, yes
values, or their number in scalar @h{...} = (...)
context
exists key true when the key exists exists
defined key true when its value is defined defined $h{k}
delete 1 or more keys the value removed; with several delete yes
keys, the values, or the last in
scalar context
keys none the keys; their number in scalar keys
context
values none the values; their number in scalar values
context
kv none a [key, value] array ref for each (keys, values)
key; their number in scalar context
count none the number of keys scalar keys
is_empty none true when there are none !%h
clear none the empty list; 0 in scalar context %h = () yes
keys, values and kv start the hash's each iterator afresh in any context, as keys does.
How the native ops behave
Defaults. An ArrayRef or HashRef slot with
handlesgets a default of[]or{}, a new one for each object, unless it has adefault, abuilder, or isrequired. The added default does not change hownewreads its arguments - a default written in a spec makesnewread an even number of arguments starting with a string as name/value pairs, this one does not - andslot_infoshows it asdefault_implicit. A default written by hand must be[]for an ArrayRef and{}for a HashRef.Not set. After the slot's clearer, or when a lazy builder returns undef, every op croaks
Cannot delegate push_tag to tags: tags is not set.Arguments. A call with the wrong number of arguments croaks:
Wrong number of arguments to get_tag (get takes 1).Frozen. On a frozen object, the ops that change the container croak
Cannot modify frozen object; the others work.Readonly. An op that changes the container cannot be delegated from a
readonlyslot: the class definition croaks. The ops that only read can.Triggers. After an op that changes the container, the slot's
triggeris called once, as the setter calls it, with the object and the container:trigger($self, $container). A trigger that dies does not undo the change.Values. The values given back are the container's own, as
@$refandvalues %$refgive them;kvgives copies. Values stored are copies.Tied and restricted containers work through the tie: a tied array's
pushandunshiftstore throughSTORE, and a restricted hash croaks for a key it does not allow, as perl does. A read-only array croaks as perl does.Prototypes. An object whose slot is empty uses its prototype's container, as its accessor would, so a change goes to the prototype's container. The frozen check is on the object called.
Weak. A
weakslot cannot have CodeRef, ArrayRef or HashRef handles (the container could be freed at once); an Object slot can.
Names, inheritance and redefinition
A delegating method is installed when the class is defined, after every slot's accessor, and the class definition croaks when its name is taken:
by a reserved name:
new,prototype,set_prototype,instance,BUILD,DEMOLISH,DESTROY,AUTOLOAD,import,unimport,isa,can,DOES,VERSION, or a special block name;by a method a slot gives the class - an accessor, reader, writer, clearer or predicate - or by another delegating method;
by a sub of the class's own.
A child class gets delegating methods of its own for the slots it inherits, at its own slot positions, so they work with multiple inheritance too. What the child defines itself - a sub, a slot of the same name - overrides an inherited delegating method, as it would override any parent method, and of two parents delegating the same name the first wins. The child can change the handles with +attr: the lists add up, and a name the child gives replaces the parent's:
object 'Base', 'logger:Object:handles(info, warn)';
object 'Quiet', extends => 'Base', '+logger:handles(info=>debug, trace)';
# Quiet: info calls debug, warn calls warn, trace calls trace
A +attr is checked again as a whole: adding readonly to a slot whose handles change its container croaks.
Defining a class again keeps its delegating methods, pointing them at the slots of the new definition, and keeps any before, after or around modifiers wrapped round them. with croaks when a role slot's methods would take a delegating method's name.
Introspection
slot_info reports has_handles, and, when it is true, handles: a hash of each installed method to what it calls - the method name, the native op (elements shown as list), or call or method for a CodeRef.
Errors when a class is defined
handles() needs at least one method for slot 'x'
Invalid method name 'log-info' in handles for slot 'x'
Invalid role name 'A-B' in handles for slot 'x'
Method 'info' appears twice in handles for slot 'x'
handles is not supported on a Str slot 'x'
handles is not supported on an untyped slot 'x'
weak slot 'x' cannot have ArrayRef handles
The default of ArrayRef slot 'tags' must be [] for handles
Unknown ArrayRef method 'frob' in handles for slot 'tags' (valid: push, pop, ...)
CodeRef handles for slot 'f' must map to call or method, not 'frob'
Cannot delegate push_tag=>push on readonly slot 'tags'
handles(role:...) needs an Object slot, 'tags' is ArrayRef
Role 'R' in handles for slot 'x' is not defined
Role 'R' in handles for slot 'x' has no methods
handles for slot 'x': method 'new' is reserved
handles for slot 'x': method 'info' is already provided by slot 'y'
You cannot overwrite a locally defined method (info) with a delegation
Slot conflict: method 'size' of slot 'size' from role 'R' is delegated in class 'C'
A role that cannot be loaded croaks as require does.
Errors when a delegating method is called
Not an object
Cannot delegate info to logger: logger is not set
Cannot delegate format to formatter: formatter is not a CODE reference
Cannot delegate push_tag to tags: tags is not an ARRAY reference
Cannot delegate get_opt to opts: opts is not a HASH reference
Wrong number of arguments to get_tag (get takes 1)
Wrong number of arguments to push_tag (push takes at least 1)
Wrong number of arguments to set_opt (set takes key/value pairs)
Cannot modify frozen object
Inheritance (extends)
Classes can inherit slots from a parent class using the extends key:
object 'Animal', 'name:Str:required', 'sound:Str';
object 'Dog',
extends => 'Animal',
'breed:Str';
my $dog = new Dog name => 'Rex', sound => 'Woof', breed => 'Lab';
print $dog->name; # "Rex" (inherited from Animal)
print $dog->breed; # "Lab" (own slot)
print $dog->isa('Animal'); # true
The parent class must already be defined. All parent slots are copied into the child class, and @ISA is set up automatically. The child can override any inherited slot by redefining it:
object 'StrictDog',
extends => 'Animal',
'name:Str:required:readonly', # override with readonly
'breed:Str:required';
Multiple Inheritance
Pass an arrayref to extends to inherit from multiple parents:
object 'Swimmer', 'stroke:Str';
object 'Runner', 'pace:Num';
object 'Triathlete',
extends => ['Swimmer', 'Runner'],
'event:Str';
my $t = new Triathlete stroke => 'freestyle', pace => 7.5, event => '70.3';
print $t->isa('Swimmer'); # true
print $t->isa('Runner'); # true
When multiple parents define a slot with the same name, the first parent in the list wins. The child can always override any inherited slot.
Multi-level Inheritance
Inheritance chains work as expected:
object 'Grandparent', 'family:Str';
object 'Parent', extends => 'Grandparent', 'middle:Str';
object 'Child', extends => 'Parent', 'first:Str';
my $c = new Child family => 'Smith', middle => 'J', first => 'Alice';
print $c->isa('Grandparent'); # true
Object::Proto::register_type($name, $check, $coerce)
Register a custom type for use in slot specifications.
# Simple check
Object::Proto::register_type('PositiveInt', sub {
my $val = shift;
return $val =~ /^\d+$/ && $val > 0;
});
# With coercion
Object::Proto::register_type('TrimmedStr',
sub { defined $_[0] && !ref $_[0] }, # check
sub { my $v = shift; $v =~ s/^\s+|\s+$//g; $v } # coerce
);
# Now use in define
object 'Counter',
'value:PositiveInt',
'label:TrimmedStr';
A registered type takes precedence over a built-in type of the same name, so a type you register keeps its meaning if a later release of Object::Proto adds a built-in with that name. Type names are resolved when a class is defined: a class defined before the registration keeps the built-in. This applies equally to types registered from C (see below).
Object::Proto::has_type($name)
Returns true if a type is registered (built-in or custom).
if (Object::Proto::has_type('Email')) { ... }
Object::Proto::list_types()
Returns arrayref of all registered type names.
my $types = Object::Proto::list_types();
# ['Any', 'Defined', 'Str', 'Int', ... 'PositiveInt']
XS-Level Type Registration (for XS modules)
External XS modules can register types with C-level check functions that bypass Perl callback overhead entirely (~5 cycles vs ~100 cycles).
Linking
Your XS module needs to link against the Object::Proto module. The functions are exported with PERL_CALLCONV visibility.
Include object_types.h in your XS module:
#include "object_types.h"
Object::Proto uses ExtUtils::Depends so downstream XS modules can automatically find the headers and link flags. In your Makefile.PL:
# Makefile.PL
use ExtUtils::Depends;
my $pkg = ExtUtils::Depends->new('MyTypes', 'Object::Proto');
WriteMakefile(
$pkg->get_makefile_vars,
...
);
C API Reference
object_register_type_xs
void object_register_type_xs(pTHX_ const char *name,
ObjectTypeCheckFunc check,
ObjectTypeCoerceFunc coerce);
Register a type with C-level check and optional coercion functions. Call from your BOOT section. The type name can then be used in Object::Proto::define() slot specifications.
Parameters:
name- Type name (e.g., "PositiveInt", "Email")check- C function to validate values (required)coerce- C function to coerce values (optional, pass NULL)
ObjectTypeCheckFunc
typedef bool (*ObjectTypeCheckFunc)(pTHX_ SV *val);
Type check function signature. Return true if value passes the check.
ObjectTypeCoerceFunc
typedef SV* (*ObjectTypeCoerceFunc)(pTHX_ SV *val);
Type coercion function signature. Return the coerced value (may be the same SV or a new mortal). Return NULL if coercion fails.
object_get_registered_type
RegisteredType* object_get_registered_type(pTHX_ const char *name);
Look up a registered type by name. Returns NULL if not found. Useful for introspection or chaining type checks.
object_register_type_xs_ex
void object_register_type_xs_ex(pTHX_ const char *name,
ObjectTypeCheckFuncEx check,
ObjectTypeCoerceFuncEx coerce,
void *data);
User-data variant. When a single pair of check/coerce C functions needs to serve multiple dynamically-created types (e.g., enums, parameterized types), use this variant which passes a per-type opaque data pointer on every call.
Parameters:
name- Type namecheck- C function to validate values (receives data pointer)coerce- C function to coerce values (optional, pass NULL)data- Opaque pointer passed to check/coerce on every call
ObjectTypeCheckFuncEx
typedef bool (*ObjectTypeCheckFuncEx)(pTHX_ SV *val, void *data);
Check signature with user-data. The data pointer is whatever was passed to object_register_type_xs_ex.
ObjectTypeCoerceFuncEx
typedef SV* (*ObjectTypeCoerceFuncEx)(pTHX_ SV *val, void *data);
Coerce signature with user-data.
Complete Example
/* MyTypes.xs */
#define PERL_NO_GET_CONTEXT
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
#include "object_types.h"
static bool check_positive_int(pTHX_ SV *val) {
if (!SvIOK(val) && !(SvPOK(val) && looks_like_number(val)))
return false;
return SvIV(val) > 0;
}
static bool check_email(pTHX_ SV *val) {
if (SvROK(val)) return false;
STRLEN len;
const char *pv = SvPV(val, len);
const char *at = memchr(pv, '@', len);
return at && at != pv && at != pv + len - 1;
}
static SV* coerce_trim(pTHX_ SV *val) {
STRLEN len;
const char *pv = SvPV(val, len);
const char *start = pv;
const char *end = pv + len;
while (start < end && isSPACE(*start)) start++;
while (end > start && isSPACE(*(end-1))) end--;
return sv_2mortal(newSVpvn(start, end - start));
}
MODULE = MyTypes PACKAGE = MyTypes
BOOT:
object_register_type_xs(aTHX_ "PositiveInt", check_positive_int, NULL);
object_register_type_xs(aTHX_ "Email", check_email, NULL);
object_register_type_xs(aTHX_ "TrimmedStr", NULL, coerce_trim);
Usage in Perl:
use MyTypes; # Registers types in BOOT
use Object::Proto;
object 'User',
'id:PositiveInt:required',
'email:Email',
'bio:TrimmedStr';
my $user = new User id => 42, email => 'user@example.com';
User-Data Example: Enum Type Registration
typedef struct {
HV *valid_values; /* value -> name lookup */
HV *lc_name2val; /* lc(name) -> value for coercion */
} EnumTypeData;
static bool enum_check(pTHX_ SV *val, void *data_ptr) {
EnumTypeData *etd = (EnumTypeData *)data_ptr;
STRLEN len;
const char *pv = SvPV(val, len);
return hv_exists(etd->valid_values, pv, len);
}
static SV *enum_coerce(pTHX_ SV *val, void *data_ptr) {
EnumTypeData *etd = (EnumTypeData *)data_ptr;
STRLEN len;
const char *pv = SvPV(val, len);
/* case-insensitive name -> value lookup */
char *lc = savepvn(pv, len);
STRLEN i;
for (i = 0; i < len; i++) lc[i] = toLOWER(lc[i]);
SV **found = hv_fetch(etd->lc_name2val, lc, len, 0);
Safefree(lc);
return found ? sv_mortalcopy(*found) : val;
}
/* In BOOT or at parse time: */
EnumTypeData *etd;
Newxz(etd, 1, EnumTypeData);
etd->valid_values = newHV();
etd->lc_name2val = newHV();
/* ... populate HVs ... */
object_register_type_xs_ex(aTHX_ "Color",
enum_check, enum_coerce, (void*)etd);
Dispatch Order
The same enum_check and enum_coerce functions serve every enum type; only the EnumTypeData differs.
Dispatch Order
When checking a value, Object::Proto tries handlers in this order:
- 1.
check_ex(C function with user-data) - ~5 cycles - 2.
check(C function) - ~5 cycles - 3.
perl_check(Perl callback from register_type) - ~100 cycles
Coercion follows the same priority: coerce_ex, then coerce, then perl_coerce.
Performance Tiers
Type Source Check Cost Total Overhead
--------------------------------------------------------
Built-in (Str, Int) ~0 cycles inline switch
Registered C function ~5 cycles function pointer
Perl callback ~100 cycles call_sv overhead
new $class @args
Create a new object. Supports positional or named arguments.
my $cat = new Cat 'Whiskers', 3; # positional
my $cat = new Cat name => 'Whiskers'; # named
$obj->prototype
Get the prototype object (or undef if none).
$obj->set_prototype($proto)
Set the prototype object. Fails if object is frozen.
Object::Proto::prototype_chain($obj)
Return the full prototype chain as an arrayref, starting from $obj and following each prototype link. Detects and stops on circular references.
my $chain = Object::Proto::prototype_chain($cat);
# [$cat, $proto, $proto_of_proto, ...]
Object::Proto::prototype_depth($obj)
Return the depth of the prototype chain (number of prototypes above this object). Returns 0 if the object has no prototype.
my $depth = Object::Proto::prototype_depth($cat); # 0, 1, 2, ...
Object::Proto::has_own_property($obj, $property)
Return true if the object has a defined value for the given property in its own slots (not inherited via prototype chain).
if (Object::Proto::has_own_property($cat, 'name')) { ... }
$obj->lock
Prevent adding new properties. Can be unlocked.
$obj->unlock
Allow adding new properties again. Fails if frozen.
$obj->freeze
Permanently prevent modifications. Cannot be undone.
$obj->is_frozen
Returns true if object is frozen.
$obj->is_locked
Returns true if object is locked (but may not be frozen).
Object::Proto::clone($obj)
Create a shallow copy of an object. All property values are copied, but references share the same underlying referent. The clone is a fresh object that is NOT frozen or locked, even if the original was.
my $original = new Cat name => 'Whiskers', age => 3;
Object::Proto::freeze($original);
my $clone = Object::Proto::clone($original);
$clone->age(4); # works - clone is not frozen
print $clone->name; # "Whiskers"
Shallow copy means array/hash reference properties will share data:
$original->tags(['fluffy']);
my $clone = $original->clone;
push @{$clone->tags}, 'playful';
# $original->tags is now ['fluffy', 'playful']
Object::Proto::properties($class)
Return the property names for a class. In list context, returns the property names. In scalar context, returns the count.
my @props = Object::Proto::properties('Cat'); # ('name', 'age')
my $count = Object::Proto::properties('Cat'); # 2
# Check if property exists
if (grep { $_ eq 'color' } Object::Proto::properties('Cat')) {
...
}
Returns an empty list (or 0 in scalar context) for non-existent classes.
Object::Proto::slot_info($class, $property)
Return detailed metadata about a property slot. Returns a hashref with information about the slot, or undef if the class or property doesn't exist.
my $info = Object::Proto::slot_info('Person', 'name');
# Returns:
# {
# name => 'name',
# index => 1,
# type => 'Str',
# is_required => 1,
# is_readonly => 0,
# is_lazy => 0,
# has_default => 0,
# has_trigger => 0,
# has_coerce => 0,
# has_builder => 0,
# has_clearer => 0,
# has_predicate => 0,
# has_type => 1,
# }
The returned hash always contains these boolean flags:
is_required - Property must be provided in new()
is_readonly - Setter disabled after construction
is_lazy - Value computed on first access
has_default - Has a default value
has_trigger - Has a trigger callback
has_coerce - Has coercion enabled
has_builder - Has a builder method
has_clearer - Has a clearer method
has_predicate - Has a predicate method
has_type - Has a type constraint
is_weak - References stored in the slot are weakened
has_handles - Has
handles(...)delegation
Additional keys may be present depending on the slot configuration:
type - The type name (if has_type is true)
default - The default value (if has_default is true)
default_implicit - 1 when the default is the
[]or{}thathandlesadded, rather than one written in the specbuilder - The builder method name (if has_builder is true)
init_arg - The constructor argument name (if
arg(name)is used)handles - (if has_handles is true) a hash of each delegating method to what it calls: the method name for an Object slot, the native op for an ArrayRef or HashRef slot (
elementsshown aslist),callormethodfor a CodeRef slot
object 'Bag', 'tags:ArrayRef:handles(add=>push, all=>elements)';
Object::Proto::slot_info('Bag', 'tags')->{handles};
# { add => 'push', all => 'list' }
Object::Proto::parent($class)
Return the parent class(es) of a class. In scalar context, returns the first (or only) parent class name, or undef if none. In list context, returns all parent class names.
object 'Animal', 'name:Str';
object 'Dog', extends => 'Animal', 'breed:Str';
my $p = Object::Proto::parent('Dog'); # 'Animal'
my @p = Object::Proto::parent('Dog'); # ('Animal')
object 'Hybrid', extends => ['Dog', 'Cat'];
my $first = Object::Proto::parent('Hybrid'); # 'Dog'
my @all = Object::Proto::parent('Hybrid'); # ('Dog', 'Cat')
Returns undef/empty list for classes with no parent.
Object::Proto::ancestors($class)
Return all ancestor classes in breadth-first order, with duplicates removed. Useful for inspecting the full inheritance hierarchy.
object 'A', 'a:Str';
object 'B', extends => 'A', 'b:Str';
object 'C', extends => 'B', 'c:Str';
my @anc = Object::Proto::ancestors('C'); # ('B', 'A')
For multiple inheritance with diamond patterns, each ancestor appears only once (first occurrence wins):
object 'Base', 'x:Str';
object 'Left', extends => 'Base';
object 'Right', extends => 'Base';
object 'Diamond', extends => ['Left', 'Right'];
my @anc = Object::Proto::ancestors('Diamond');
# ('Left', 'Right', 'Base') -- Base appears once
Object::Proto::import_accessors($class, $prefix, $target)
Import function-style accessors for maximum performance. This enables calling accessors as name $obj instead of $obj->name, which avoids method dispatch overhead.
# In a BEGIN block so call checker sees the functions
BEGIN {
use Object::Proto;
object 'Cat', qw(name age);
Object::Proto::import_accessors('Cat'); # imports to current package
}
my $cat = new Cat 'Whiskers', 3;
# Function-style - 2.4x faster GET, 4x faster SET
my $n = name $cat;
age $cat, 4;
# Method-style still works
my $n = $cat->name;
$cat->age(4);
The optional $prefix parameter prepends a string to each imported accessor name, which is useful for avoiding name collisions when importing from multiple classes:
BEGIN {
Object::Proto::define('Dog', qw(name breed));
Object::Proto::define('Cat', qw(name color));
Object::Proto::import_accessors('Dog', 'dog_');
Object::Proto::import_accessors('Cat', 'cat_');
}
my $d = new Dog name => 'Rex', breed => 'Lab';
dog_name $d; # 'Rex'
dog_breed $d; # 'Lab'
The optional $target parameter specifies which package to import into (defaults to caller). Pass undef for $prefix to skip prefixing when specifying a target:
Object::Proto::import_accessors('Cat', undef, 'MyPackage');
Object::Proto::import_accessor($class, $prop, $alias, $target)
Import a single accessor with an optional alias name.
BEGIN {
use Object::Proto;
object 'Cat', qw(name age);
Object::Proto::import_accessor('Cat', 'name', 'get_name');
Object::Proto::import_accessor('Cat', 'age', 'set_age');
}
my $cat = new Cat 'Whiskers', 3;
my $n = get_name $cat; # same as name($cat)
set_age $cat, 4; # same as age($cat, 4)
Parameters:
$class- The class name$prop- The property name to access$alias- The function name to install (defaults to$prop)$target- Package to install into (defaults to caller)
Function-style accessors are compiled to custom ops at compile time, giving performance competitive with or faster than slot.
BUILD
Define a BUILD method in your class to run initialization code after object construction. BUILD is called automatically after new() with the fully constructed object as its argument.
package Counter;
use Object::Proto;
object 'Counter', 'count', 'label:Str';
sub BUILD {
my ($self) = @_;
$self->count(0);
}
package main;
my $c = new Counter label => 'hits';
$c->count; # 0 (set by BUILD)
All constructor arguments are applied before BUILD runs, so you can read slot values in your BUILD method:
package Derived;
object 'Derived', 'x', 'y', 'sum';
sub BUILD {
my ($self) = @_;
$self->sum(($self->x // 0) + ($self->y // 0));
}
my $d = new Derived x => 3, y => 4;
$d->sum; # 7
When a child class inherits via extends, the child's BUILD method is called (not the parent's). Call the parent's BUILD explicitly if needed.
Zero overhead: BUILD is detected lazily on first new() call, and the lookup is cached.
DEMOLISH
Define a DEMOLISH method in your class to run cleanup code when objects are destroyed. The Object::Proto module automatically installs a DESTROY wrapper that calls your DEMOLISH method.
package FileHandle;
sub DEMOLISH {
my $self = shift;
close $self->fh if $self->fh;
}
package main;
object 'FileHandle', 'fh', 'path:Str';
Zero overhead: The DESTROY wrapper is only installed for classes that define a DEMOLISH method.
SINGLETONS
Object::Proto::singleton($class)
Mark a class as a singleton. This installs a $class->instance() method that always returns the same object.
package Config;
BEGIN {
Object::Proto::define('Config', 'debug:Bool:default(0)');
Object::Proto::singleton('Config');
}
sub BUILD {
my ($self) = @_;
# initialization runs once, on first instance() call
}
package main;
my $cfg = Config->instance;
my $same = Config->instance; # same object
The instance is created lazily on the first call to instance(). If the class defines a BUILD method, it is called after construction. The class must already be defined with Object::Proto::define().
ROLES
Roles provide reusable bundles of slots and methods that can be composed into classes. Zero overhead if not used.
Object::Proto::role($name, @slot_specs)
Define a role with slots:
Object::Proto::role('Serializable', 'format:Str:default(json)');
package Serializable;
sub serialize {
my $self = shift;
return $self->format eq 'json' ? to_json($self) : to_yaml($self);
}
Object::Proto::requires($role, @method_names)
Declare methods that consuming classes must implement:
Object::Proto::requires('Serializable', 'to_hash');
Object::Proto::with($class, @roles)
Compose roles into a class:
object 'Document', 'title:Str', 'content:Str';
Object::Proto::with('Document', 'Serializable');
my $doc = new Document title => 'Test', content => 'Hello';
print $doc->format; # 'json' (from role)
print $doc->serialize; # JSON output
A role's slots may have handles(...): each class that composes the role gets the delegating methods. with croaks if one of a role slot's methods (its accessor, reader, writer, clearer or predicate) would take the name of a delegating method the class already has. To delegate every method of a role to a slot, see handles(role:Name) in "Delegation (handles)".
Object::Proto::does($obj_or_class, $role)
Check if an object or class consumes a role:
if (Object::Proto::does($doc, 'Serializable')) { ... }
METHOD MODIFIERS
Wrap existing methods with before, after, or around hooks. Zero overhead for classes that don't use modifiers.
Object::Proto::before($method, $callback)
Run code before a method. Arguments are passed to the callback.
Object::Proto::before('Person::save', sub {
my ($self) = @_;
$self->updated_at(time);
});
Object::Proto::after($method, $callback)
Run code after a method. Arguments are passed to the callback.
Object::Proto::after('Person::save', sub {
my ($self) = @_;
log_action("Saved person: " . $self->name);
});
Object::Proto::around($method, $callback)
Wrap a method. Receives $orig as first argument:
Object::Proto::around('Person::age', sub {
my ($orig, $self, @args) = @_;
if (@args) {
die "Age must be positive" if $args[0] < 0;
}
return $self->$orig(@args);
});
Multiple modifiers can be stacked:
Object::Proto::before('Class::method', \&first);
Object::Proto::before('Class::method', \&second); # runs before first
Object::Proto::after('Class::method', \&third); # runs after method
Object::Proto::after('Class::method', \&fourth); # runs after third
BENCHMARK
#!/usr/bin/env perl
use strict;
use warnings;
use Benchmark qw(:all);
use Object::Proto;
# Define classes in BEGIN so call checkers work
BEGIN {
# Object::Proto (XS) - no types
Object::Proto::define('Person', qw(name age score));
# Object::Proto (XS) - with types
Object::Proto::define('TypedPerson', 'name:Str', 'age:Int', 'score:Num');
# Import function-style accessors
Object::Proto::import_accessors('Person');
}
package PureHash {
sub new {
my ($class, %args) = @_;
return bless { name => $args{name}, age => $args{age}, score => $args{score} }, $class;
}
sub name { @_ > 1 ? $_[0]->{name} = $_[1] : $_[0]->{name} }
sub age { @_ > 1 ? $_[0]->{age} = $_[1] : $_[0]->{age} }
sub score { @_ > 1 ? $_[0]->{score} = $_[1] : $_[0]->{score} }
}
package PureArray {
use constant { NAME => 0, AGE => 1, SCORE => 2 };
sub new {
my ($class, %args) = @_;
return bless [ $args{name}, $args{age}, $args{score} ], $class;
}
sub name { @_ > 1 ? $_[0]->[NAME] = $_[1] : $_[0]->[NAME] }
sub age { @_ > 1 ? $_[0]->[AGE] = $_[1] : $_[0]->[AGE] }
sub score { @_ > 1 ? $_[0]->[SCORE] = $_[1] : $_[0]->[SCORE] }
}
print "\n\nTest: Mixed new->set->get (5 seconds)\n";
print "-" x 40, "\n";
my $r = timethese(-5, {
'Raw Hash' => sub {
my %hh = ( name => 'Alice', age => 30, score => 95.5 );
$hh{age} = 31;
my $x = $hh{age};
},
'Raw Hash Ref' => sub {
my $h = { name => 'Alice', age => 30, score => 95.5 };
$h->{age} = 31;
my $x = $h->{age};
},
'Pure Hash' => sub {
my $pure_hash = PureHash->new(name => 'Bob', age => 25, score => 88.0);
$pure_hash->age(31);
my $x = $pure_hash->age;
},
'Pure Array' => sub {
my $pure_array = PureArray->new(name => 'Bob', age => 25, score => 88.0);
$pure_array->age(31);
my $x = $pure_array->age;
},
'Object::Proto (XS OO)' => sub {
my $obj_xs = new Person name => 'Bob', age => 25, score => 88.0;
$obj_xs->age(31);
my $x = $obj_xs->age;
},
'Object::Proto (XS func)' => sub {
my $obj_xs = new Person 'Bob', 25, 88.0;
age($obj_xs, 31);
my $x = age($obj_xs);
},
'Object::Proto typed' => sub {
my $obj_typed = new TypedPerson 'Bob', 25, 88.0;
age $obj_typed, 31;
my $x = age $obj_typed;
},
});
cmpthese $r;
Test: Mixed new->set->get (5 seconds)
----------------------------------------
Benchmark: running Object::Proto (XS OO), Object::Proto (XS func), Object::Proto typed, Pure Array, Pure Hash, Raw Hash, Raw Hash Ref for at least 5 CPU seconds...
^[[B^[[BObject::Proto (XS OO): 5 wallclock secs ( 5.43 usr + 0.01 sys = 5.44 CPU) @ 3541833.27/s (n=19267573)
Object::Proto (XS func): 6 wallclock secs ( 5.38 usr + 0.01 sys = 5.39 CPU) @ 5427162.15/s (n=29252404)
Object::Proto typed: 4 wallclock secs ( 5.00 usr + 0.00 sys = 5.00 CPU) @ 5114882.60/s (n=25574413)
Pure Array: 6 wallclock secs ( 5.12 usr + 0.01 sys = 5.13 CPU) @ 2124356.53/s (n=10897949)
Pure Hash: 4 wallclock secs ( 5.00 usr + 0.01 sys = 5.01 CPU) @ 1824921.36/s (n=9142856)
Raw Hash: 5 wallclock secs ( 5.32 usr + 0.01 sys = 5.33 CPU) @ 6024884.24/s (n=32112633)
Raw Hash Ref: 3 wallclock secs ( 5.01 usr + 0.01 sys = 5.02 CPU) @ 5331773.11/s (n=26765501)
Rate Pure Hash Pure Array Object::Proto (XS OO) Object::Proto typed Raw Hash Ref Object::Proto (XS func) Raw Hash
Pure Hash 1824921/s -- -14% -48% -64% -66% -66% -70%
Pure Array 2124357/s 16% -- -40% -58% -60% -61% -65%
Object::Proto (XS OO) 3541833/s 94% 67% -- -31% -34% -35% -41%
Object::Proto typed 5114883/s 180% 141% 44% -- -4% -6% -15%
Raw Hash Ref 5331773/s 192% 151% 51% 4% -- -2% -12%
Object::Proto (XS func) 5427162/s 197% 155% 53% 6% 2% -- -10%
Raw Hash 6024884/s 230% 184% 70% 18% 13% 11% --
... If you only instantiate once and then only set/get inside the benchmark
Test: Mixed set/get (5 seconds)
----------------------------------------
Benchmark: running Object::Proto (XS OO), Object::Proto (XS func), Object::Proto typed, Pure Array, Pure Hash, Raw Hash, Raw Hash Ref for at least 5 CPU seconds...
Object::Proto (XS OO): 5 wallclock secs ( 5.17 usr + 0.00 sys = 5.17 CPU) @ 13893769.44/s (n=71830788)
Object::Proto (XS func): 5 wallclock secs ( 5.13 usr + -0.01 sys = 5.12 CPU) @ 32693120.12/s (n=167388775)
Object::Proto typed: 4 wallclock secs ( 5.00 usr + 0.02 sys = 5.02 CPU) @ 31742847.21/s (n=159349093)
Pure Array: 5 wallclock secs ( 5.02 usr + 0.02 sys = 5.04 CPU) @ 7287556.94/s (n=36729287)
Pure Hash: 6 wallclock secs ( 5.30 usr + -0.00 sys = 5.30 CPU) @ 6991138.87/s (n=37053036)
Raw Hash: 5 wallclock secs ( 5.22 usr + 0.02 sys = 5.24 CPU) @ 25955432.82/s (n=136006468)
Raw Hash Ref: 5 wallclock secs ( 5.33 usr + 0.02 sys = 5.35 CPU) @ 24923303.55/s (n=133339674)
Rate Pure Hash Pure Array Object::Proto (XS OO) Raw Hash Ref Raw Hash Object::Proto typed Object::Proto (XS func)
Pure Hash 6991139/s -- -4% -50% -72% -73% -78% -79%
Pure Array 7287557/s 4% -- -48% -71% -72% -77% -78%
Object::Proto (XS OO) 13893769/s 99% 91% -- -44% -46% -56% -58%
Raw Hash Ref 24923304/s 256% 242% 79% -- -4% -21% -24%
Raw Hash 25955433/s 271% 256% 87% 4% -- -18% -21%
Object::Proto typed 31742847/s 354% 336% 128% 27% 22% -- -3%
Object::Proto (XS func) 32693120/s 368% 349% 135% 31% 26% 3% --
Delegation
bench/handles.pl compares handles(...) methods with the perl they replace: a hand-written delegating sub such as sub info { my $self = shift; $self->logger->info(@_) }, and the same code written out where it is used. One run (figures vary between runs by about 10%):
Method delegation: $svc->info(1)
Rate perl sub handles written out
perl sub 36193/s -- -32% -43%
handles 52890/s 46% -- -17%
written out 63747/s 76% 21% --
CodeRef delegation: $svc->format(1) and $svc->fire(1)
Rate perl sub call perl sub method handles method handles call written out
perl sub call 31825/s -- -17% -30% -30% -61%
perl sub method 38559/s 21% -- -15% -16% -52%
handles method 45230/s 42% 17% -- -1% -44%
handles call 45658/s 43% 18% 1% -- -43%
written out 80637/s 153% 109% 78% 77% --
ArrayRef: push and pop
Rate written out handles
written out 44080/s -- -10%
handles 49211/s 12% --
ArrayRef: count
Rate written out handles
written out 104181/s -- -8%
handles 112991/s 8% --
ArrayRef: get
Rate written out handles
written out 70173/s -- -30%
handles 100797/s 44% --
HashRef: get and set
Rate handles written out
handles 40851/s -- -11%
written out 45654/s 12% --
A handles method is always faster than the delegating sub it replaces. Against code written out in place, method and native delegation are roughly level - a little slower for some ops and faster for others, and the order changes between runs - while adding the checks described above. A code ref called in place stays faster than any method that calls it, because calling code from C starts a run loop of its own.
AUTHOR
LNATION <email@lnation.org>
LICENSE
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.