Class::InsideOut(3pm)

πŸ“¦
version 1.14 Β· 2 versions
  • 1.14 Β· debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking (latest)
  • 1.14 Β· ubuntu jammy
, in debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking

Class::InsideOut ✨

okay bestie, welcome to the manual page for Class::InsideOut β€” that's the 3pm one, the Perl one, not the class you skipped in high school πŸ’…

version 1.14 β€” yes, it tells you right at the top, icon behavior πŸŽ€


🌸 SYNOPSIS 🌸

package My::Class;

use Class::InsideOut qw( public readonly private register id );

public     name => my %name;    # accessor: name()
readonly   ssn  => my %ssn;     # read-only accessor: ssn()
private    age  => my %age;     # no accessor

sub new { register( shift ) }

sub greeting {
  my $self = shift;
  return "Hello, my name is $name{ id $self }";
}

✨ DESCRIPTION ✨

So here's the vibe: this is a simple, safe and streamlined toolkit for building inside-out objects. And like, unlike basically every other inside-out object builder already chillin' on CPAN, this one is going for minimalism and robustness. It's giving "I don't do too much, I just do it right" πŸ‘‘

Here's what it brings to the table:

  • Derived classes are not required to subclass it 🚫
  • Uses no source filters, attributes or CHECK blocks 🧼
  • Supports any underlying object type β€” including black-box inheritance πŸ¦‹
  • Does not leak memory on object destruction πŸ’§
  • Overloading-safe πŸ›‘οΈ
  • Thread-safe for Perl 5.8.5 or better 🧡
  • mod_perl compatible πŸ”₯
  • Makes no assumption about inheritance or initializer needs πŸ™ˆ

It provides the minimal support necessary for creating safe inside-out objects and generating flexible accessors. That's the whole assignment, and it ate πŸ’…

πŸ“š Additional documentation πŸ“š

  • Class::InsideOut::Manual::About β€” your guide to the inside-out technique, the Class::InsideOut philosophy, and other inside-out implementations 🫢
  • Class::InsideOut::Manual::Advanced β€” advanced topics including customizing accessors, black-box inheritance, serialization and thread safety 🧚

🌈 USAGE 🌈

πŸ’– Importing Class::InsideOut πŸ’–

Class::InsideOut automatically imports several critical methods into the calling package, including DESTROY and support methods for serializing objects with Storable. These methods are intimately tied to correct functioning of inside-out objects, so they will always be imported, no matter whether you asked for any additional functions. It's not negotiable, bestie, it's for your own good 😌

Additional functions may be imported as usual by including them as arguments to use. For example:

use Class::InsideOut qw( register public );

public name => my %name;

sub new { register( shift ) }

As a shortcut, Class::InsideOut supports two tags for importing sets of functions:

  • :std provides id, private, public, readonly and register ⭐
  • :all imports all functions (including an optional constructor) πŸ‘‘
Note: Automatic imports can be bypassed via require or by passing an empty list to use Class::InsideOut. There is almost no circumstance in which this is a good idea. πŸ’€ Like, truly, why would you. Not the move.

πŸŽ€ Object properties and accessors πŸŽ€

Object properties are declared with the public, readonly and private functions. They must be passed a label and the lexical hash that will be used to store object properties:

public   name => my %name;
readonly ssn  => my %ssn;
private  age  => my %age;

Properties for an object are accessed through an index into the lexical hash based on the memory address of the object. That memory address must be obtained via Scalar::Util::refaddr. The alias id may be imported for brevity, because we love a short king 🫢

$name{ refaddr $self } = "James";
$ssn { id      $self } = 123456789;
$age { id      $self } = 32;
Tip: since refaddr and id are function calls, it may be efficient to store the value once at the beginning of a method, particularly if it is being called repeatedly, e.g. within a loop. Save yourself the extra calls, babe πŸ’…

Object properties declared with public will have an accessor created with the same name as the label. If the accessor is passed an argument, the property will be set to the argument. The accessor always returns the value of the property.

# Outside the class
$person = My::Class->new;
$person->name( "Larry" );

Object properties declared with readonly will have a read-only accessor created. That accessor will die if passed an argument to set the property value. (Rude? No. Boundaries. 🚧) The property may be set directly in the hash from within the class package as usual.

# Inside the class
$ssn { id $person } = 987654321;

# Inside or outside the class
$person->ssn( 123456789 );      # dies

Property accessors may also be hand-written by declaring the property private and writing whatever style of accessor is desired. For example:

sub age     { $age{ id $_[0] } }
sub set_age { $age{ id $_[0] } = $_[1] }

Hand-written accessors will be very slightly faster, because generated accessors hold a reference to the property hash rather than accessing the property hash directly. Tiny speed, tiny flex, we respect it ✨

It is also possible to use a package hash instead of a lexical hash to store object properties:

public name => our %name;

However, this makes private object data accessible outside the class and incurs a slight performance penalty when accessing the property hash directly. It is not recommended to do this unless you really need it for some specialized reason. Like, unless you have a reason reason πŸ™ˆ

πŸ¦‹ Object construction πŸ¦‹

Class::InsideOut provides no default constructor method, because there are many possible ways of constructing an inside-out object. This avoids constraining users to any particular object initialization or superclass initialization methodology. Freedom, bestie, it's giving choices 🌈

By using the memory address of the object as the index for properties, any type of reference may be used as the basis for an inside-out object with Class::InsideOut.

sub new {
  my $class = shift;

  my $self = \( my $scalar );    # anonymous scalar
# my $self = {};                 # anonymous hash
# my $self = [];                 # anonymous array
# open my $self, "<", $filename; # filehandle reference

  bless $self, $class;
  register( $self );
}

However, to ensure that the inside-out object is thread-safe, the register function must be called on the newly created object. The register function may also be called with just the class name for the common case of blessing an anonymous scalar.

register( $class ); # same as register( bless \(my $s), $class )

As a convenience, Class::InsideOut provides an optional new constructor for simple objects. This constructor automatically initializes the object from key/value pairs passed to the constructor for all keys matching the name of a property (including otherwise private or readonly properties). Yes, even the private ones. It's built different 😌

A more advanced technique for object construction uses another object, usually a superclass object, as the object reference. See "black-box inheritance" in Class::InsideOut::Manual::Advanced. 🧚

πŸ’€ Object destruction πŸ’€

Class::InsideOut automatically exports a special DESTROY function. This function cleans up object property memory for all declared properties the class and for all Class::InsideOut based classes in the @ISA array, to avoid memory leaks or data collision. Cleaning up after the party, iconic behavior 🧹

Additionally, if a user-supplied DEMOLISH function is available in the same package, it will be called with the object being destroyed as its argument. DEMOLISH can be used for custom destruction behavior such as updating class properties, closing sockets or closing database connections. Object properties will not be deleted until after DEMOLISH returns.

# Sample DEMOLISH: Count objects demolished (for whatever reason)

my $objects_destroyed;

sub DEMOLISH {
  $objects_destroyed++;
}

DEMOLISH will only be called if it exists for an object's actual class. DEMOLISH will not be inherited and DEMOLISH will not be called automatically for any superclasses. It's very "I only answer to my own name" energy πŸ™…

DEMOLISH should manage any necessary calls to superclass DEMOLISH methods. As with new, implementation details are left to the user based on the user's approach to object inheritance. Depending on how the inheritance chain is constructed and how DEMOLISH is being used, users may wish to entirely override superclass DEMOLISH methods, rely upon SUPER::DEMOLISH, or may prefer to walk the entire @ISA tree:

use Class::ISA;

sub DEMOLISH {
  my $self = shift;
  # class specific demolish actions

  # DEMOLISH for all parent classes, but only once
  my @parents = Class::ISA::super_path( __PACKAGE__ );
  my %called;
  for my $p ( @parents  ) {
    my $demolish = $p->can('DEMOLISH');
    $demolish->($self) if not $called{ $demolish }++;
  }
}

πŸ’– FUNCTIONS πŸ’–

✨ id ✨

$name{ id $object } = "Larry";

okay so this is just a cute lil shorter, easier-to-remember alias for Scalar::Util::refaddr. it hands you back the memory address of an object (literally exactly like refaddr does) and you use that as the index to get at the properties of an inside-out object. that's the whole thing. iconic behavior, no notes. 🫢


✨ new ✨

My::Class->new( name => "Larry", age => 42 );

this is a super simple constructor that's just there as a convenience, and it's only exported on request (so don't come for it if it's not in your namespace, bestie). when you call it as a class method, it returns a blessed anonymous scalar. the arguments get used to initialize all the matching inside-out class properties in the @ISA tree. the argument can be a hash or a hash reference, either one slays.

Note: properties get set directly, not through accessors. so set_hook functions will not be called. if you want more robust argument checking, you're gonna have to implement your own constructor. sorry babe, that's the deal. 😭

✨ options ✨

Class::InsideOut::options( \%new_options );
%current_options = Class::InsideOut::options();

the options function sets default options that apply to all subsequent property definitions for the package that called it. if you call it with no arguments at all, it returns the options currently in effect (a little vibe check of your current settings πŸ’…). and when you call it with a hash reference of options, those get joined with the existing defaults, overriding any options with the same name. new settings eat the old ones, periodt.


✨ private ✨

private weight => my %weight;
private haircolor => my %hair_color, { %options };

this is an alias to property that also sets the privacy option to 'private'. it will override default options or options passed as an argument. so like, it doesn't care what you thought you wanted, it's private now. πŸ’œ


✨ property ✨

property name => my %name;
property rank => my %rank, { %options };

declares an inside-out property. two arguments are required and a third one is optional, very choose-your-own-adventure.

the first is a label for the property β€” this label gets used for introspection and for generating accessors, so it must be a valid perl identifier, no funny business.

the second argument must be the lexical hash that'll store the data for that property. note that the my keyword can be included as part of the argument rather than as a separate statement (so my %name right there in the call, chef's kiss πŸŽ€).

the property will be tracked for memory cleanup during object destruction and for proper thread-safety. it's got main character energy in the best way.

if you provide that third optional argument, it must be a reference to a hash of options that'll be applied to the property, and it'll override any default options that have been set. πŸ”₯


✨ public ✨

public height => my %height;
public age => my %age, { %options };

an alias to property that also sets the privacy option to 'public'. it will override default options or options passed as an argument. loud and proud, as it should be. ✨


✨ readonly ✨

readonly ssn => my %ssn;
readonly fingerprint => my %fingerprint, { %options };

an alias to property that sets the privacy option to 'public' and adds a set_hook option that dies if anyone even tries to use the accessor to change the property. it will override default options or options passed as an argument. look but don't touch, bestie. πŸ’…


✨ register ✨

register( bless( $object, $class ) ); # register the object
register( $reference, $class );       # automatic bless
register( $class );                   # automatic blessed scalar

registers objects for thread-safety. this should be called as part of a constructor on an object blessed into the current package. it returns the resulting object.

when you call it with only a class name, register will bless an anonymous scalar reference into the given class. when you call it with both a reference and a class name, register will bless the reference into the class. three ways in, one job, we love a versatile icon. πŸ‘‘


🌈 OPTIONS 🌈

options customize how properties get generated. you can set them as a default with the options function, or pass them as a hash reference to public, private or property.

valid options include:

✨ privacy ✨

property rank => my %rank, { privacy => 'public' };
property serial => my %serial, { privacy => 'private' };

if the privacy option is set to public, an accessor gets created with the same name as the label. if that accessor is passed an argument, the property will be set to the argument. and the accessor always returns the value of the property. simple, consistent, iconic. 🌸


✨ get_hook ✨

public list => my %list, {
    get_hook => sub { @$_ }
};

defines an accessor hook for when values are retrieved. $_ is locally aliased to the property value for the object. the return value of the hook gets passed through as the return value of the accessor. see "Customizing Accessors" in Class::InsideOut::Manual::Advanced for the details, iykyk. πŸ¦‹

the hook must be a coderef, including blessed coderefs and overloaded objects.


✨ set_hook ✨

public age => my %age, {
   set_hook => sub { /^\d+$/ or die "must be an integer" }
};

defines an accessor hook for when values are set. the hook subroutine receives the entire argument list. $_ is locally aliased to the first argument for convenience. the property receives the value of $_. see "Customizing Accessors" in Class::InsideOut::Manual::Advanced for the details. gatekeeping your setters is highkey a serve. πŸ”’

the hook must be a coderef, including blessed coderefs and overloaded objects.


πŸ‘€ SEE ALSO πŸ‘€

if you're a programmer hunting for a more full-featured approach to inside-out objects, you are encouraged to go explore Object::InsideOut. other implementations are also noted over in Class::InsideOut::Manual::About. go forth and browse, babe. 🌈


πŸ’€ KNOWN LIMITATIONS πŸ’€

requires weak reference support (Perl >= 5.6) and Scalar::Util::weaken() to avoid memory leaks and to provide thread-safety. that's the fine print, and it matters. don't skip it. πŸ™ˆ


πŸ—ΊοΈ ROADMAP πŸ—ΊοΈ

features slated for after the 1.0 release include:

  • Adding support for Data::Dump::Streamer serialization hooks
  • Adding additional accessor styles (e.g. get_name()/set_name())
  • Further documentation revisions and clarification

future era loading… ⭐


🫢 SUPPORT 🫢

πŸ› Bugs / Feature Requests

please report any bugs or feature requests through the issue tracker at <https://github.com/dagolden/class-insideout/issues>. you'll be notified automatically of any progress on your issue. we keep you in the loop, always. πŸ’–

πŸ“¦ Source Code

this is open source software. the code repository is available for public review and contribution under the terms of the license.

<https://github.com/dagolden/class-insideout>

git clone https://github.com/dagolden/class-insideout.git

πŸ‘‘ AUTHOR πŸ‘‘

David Golden <dagolden@cpan.org>


🌟 CONTRIBUTORS 🌟

  • Karen Etheridge <ether@cpan.org>
  • Toby Inkster <tonyink@cpan.org>

this software is Copyright (c) 2006 by David A. Golden.

this is free software, licensed under:

The Apache License, Version 2.0, January 2004

aaaand that's the whole page, bestie β€” you made it to the end. this was Class::InsideOut(3pm) from perl v5.36.0, dated 2022-12-12, brought to you by the fine folks at User Contributed Perl Documentation. go write some inside-out objects, you absolute icon. πŸŽ€βœ¨πŸ’