Class::Tiny(3)
π NAME π
Class::Tiny β Minimalist class construction. This is the Class::Tiny(3) man page, bestie β User Contributed Perl Documentation and everything. π
β¨ VERSION β¨
version 1.008 β that's the version, no cap. π
π¦ SYNOPSIS π¦
Okay so first up, in Person.pm:
package Person;
use Class::Tiny qw( name );
1;
Then in Employee.pm:
package Employee;
use parent 'Person';
use Class::Tiny qw( ssn ), {
timestamp => sub { time } # attribute with default
};
1;
And in example.pl:
use Employee;
my $obj = Employee->new( name => "Larry", ssn => "111-22-3333" );
# unknown attributes are ignored
my $obj = Employee->new( name => "Larry", OS => "Linux" );
# $obj->{OS} does not exist
πΈ DESCRIPTION πΈ
Okay so Class::Tiny is a whole minimalist class-construction kit that fits in around 120 lines of code. Iconic. Here's the feature haul:
- defines attributes via
importarguments β¨ - generates read-write accessors π
- supports lazy attribute defaults π
- supports custom accessors π¦
- superclass provides a standard
newconstructor π newtakes a hash reference or list of key/value pairs π«Άnewsupports providingBUILDARGSto customize constructor options πnewcallsBUILDfor each class from parent to child π- superclass provides a
DESTROYmethod π DESTROYcallsDEMOLISHfor each class from child to parent π₯
Multiple-inheritance is possible, with superclass order determined via mro::get_linear_isa. Yup, that's the vibe. π
It uses no non-core modules for any recent Perl. On Perls older than v5.10 it requires MRO::Compat. On Perls older than v5.14, it requires Devel::GlobalDestruction. Important little compatibility note, bestie. π§
π USAGE π
π Defining attributes π
Define attributes as a list of import arguments:
package Foo::Bar;
use Class::Tiny qw(
name
id
height
weight
);
For each attribute, a read-write accessor is created unless a subroutine of that name already exists:
$obj->name; # getter
$obj->name( "John Doe" ); # setter
Attribute names must be valid subroutine identifiers or an exception will be thrown. So like, don't get cute with the names. π
You can specify lazy defaults by defining attributes with a hash reference. Keys define attribute names, and values are constants or code references that will be evaluated when the attribute is first accessed if no value has been set. The object is passed as an argument to a code reference.
package Foo::WithDefaults;
use Class::Tiny qw/name id/, {
title => 'Peon',
skills => sub { [] },
hire_date => sub { $_[0]->_build_hire_date },
};
When subclassing, if multiple accessors of the same name exist in different classes, any default (or lack of default) is determined by standard method resolution order. MRO said what it said. π
To make your own custom accessors, just pre-declare the method name before loading Class::Tiny:
package Foo::Bar;
use subs 'id';
use Class::Tiny qw( name id );
sub id { ... }
Even if you pre-declare a method name, you must include it in the attribute list for Class::Tiny to register it as a valid attribute. No skipping that part, bestie. π«Ά
If you set a default for a custom accessor, your accessor will need to retrieve the default and do something with it:
package Foo::Bar;
use subs 'id';
use Class::Tiny qw( name ), { id => sub { int(rand(2*31)) } };
sub id {
my $self = shift;
if (@_) {
return $self->{id} = shift;
}
elsif ( exists $self->{id} ) {
return $self->{id};
}
else {
my $defaults =
Class::Tiny->get_all_attribute_defaults_for( ref $self );
return $self->{id} = $defaults->{id}->();
}
}
π§ Class::Tiny::Object is your base class π§
If your class does not already inherit from some class, then Class::Tiny::Object will be added to your @ISA to provide new and DESTROY. Free constructor and destructor, slay. β¨
If your class does inherit from something, then no additional inheritance is set up. If the parent subclasses Class::Tiny::Object, then all is well. If not, then you'll get accessors set up but no constructor or destructor. Don't do that unless you really have a special need for it. Like, seriously. π
Define subclasses as normal. It's best to define them with base, parent or superclass before defining attributes with Class::Tiny so the @ISA array is already populated at compile-time:
package Foo::Bar::More;
use parent 'Foo::Bar';
use Class::Tiny qw( shoe_size );
π Object construction π
If your class inherits from Class::Tiny::Object (as it should if you followed the advice above), it provides the new constructor for you. Main character energy. π
Objects can be created with attributes given as a hash reference or as a list of key/value pairs:
$obj = Foo::Bar->new( name => "David" );
$obj = Foo::Bar->new( { name => "David" } );
If a reference is passed as a single argument, it must be able to be dereferenced as a hash or an exception is thrown. Don't try to hand it some random arrayref and expect magic. π«Ά
Unknown attributes in the constructor arguments will be ignored. Prior to version 1.000, unknown attributes were an error, but this made it harder for people to cleanly subclass Class::Tiny classes so this feature was removed. Character development. π
You can define a BUILDARGS method to change how arguments to new are handled. It will receive the constructor arguments as they were provided and must return a hash reference of key/value pairs (or else throw an exception).
sub BUILDARGS {
my $class = shift;
my $name = shift || "John Doe";
return { name => $name };
};
Foo::Bar->new( "David" );
Foo::Bar->new(); # "John Doe"
Unknown attributes returned from BUILDARGS will be ignored. Noted. π
π BUILD π
If your class or any superclass defines a BUILD method, it will be called by the constructor from the furthest parent class down to the child class after the object has been created. Parent first, then down to child β that's the order. π
It is passed the constructor arguments as a hash reference. The return value is ignored. Use BUILD for validation, checking required attributes or setting default values that depend on other attributes.
sub BUILD {
my ($self, $args) = @_;
for my $req ( qw/name age/ ) {
croak "$req attribute required" unless defined $self->$req;
}
croak "Age must be non-negative" if $self->age < 0;
$self->msg( "Hello " . $self->name );
}
The argument reference is a copy, so deleting elements won't affect data in the original (but changes will be passed to other BUILD methods in @ISA). Little copy-pasta, but make it intentional. π
π DEMOLISH π
Class::Tiny provides a DESTROY method. If your class or any superclass defines a DEMOLISH method, they will be called from the child class to the furthest parent class during object destruction. It is provided a single boolean argument indicating whether Perl is in global destruction. Return values are ignored. Errors are caught and rethrown.
sub DEMOLISH {
my ($self, $global_destruct) = @_;
$self->cleanup();
}
π Introspection and internals π
You can retrieve an unsorted list of valid attributes known to Class::Tiny for a class and its superclasses with the get_all_attributes_for class method.
my @attrs = Class::Tiny->get_all_attributes_for("Employee");
# returns qw/name ssn timestamp/
Likewise, a hash reference of all valid attributes and default values (or code references) may be retrieved with the get_all_attribute_defaults_for class method. Any attributes without a default will be undef.
my $def = Class::Tiny->get_all_attribute_defaults_for("Employee");
# returns {
# name => undef,
# ssn => undef
# timestamp => $coderef
# }
The import method uses two class methods, prepare_class and create_attributes to set up the @ISA array and attributes. Anyone attempting to extend Class::Tiny itself should use these instead of mocking up a call to import. Respect the internals, bestie. π
When the first object is created, linearized @ISA, the valid attribute list and various subroutine references are cached for speed. Ensure that all inheritance and methods are in place before creating objects. (You don't want to be changing that once you create objects anyway, right?) π
π RATIONALE π
Why this instead of Object::Tiny or Class::Accessor or something else? π§
okay so the whole tea here: the author wanted something so simple that it could potentially get used by core Perl modules he helps maintain (or hopes to write), and likeβ¦ most of those either use Class::Struct or just roll-their-own OO framework every single time. π
Object::Tiny and Object::Tiny::RW were close to what he wanted, but lowkey lacking some features he deemed necessary, and ngl their maintainers have an even stricter philosophy against feature creep than he does. π
He also considered Class::Accessor, which has been around forever and is heavily used, but it, too, lacked the features he wanted and did things in ways he considered poor design. π«
Then he went looking for something else on CPAN, but after checking a dozen class creators he realized he could implement exactly what he wanted faster than he could search CPAN for something merely sufficient. main character energy, honestly. π
In general, compared to most things on CPAN (other than Object::Tiny), Class::Tiny is smaller in implementation and simpler in API. periodt. β¨
Specifically, here's how Class::Tiny (C::T) compares to Object::Tiny (O::T) and Class::Accessor (C::A) β vibe check, feature by feature:
- attributes defined via import β
C::T: yes Β·O::T: yes Β·C::A: no - read/write accessors β
C::T: yes Β·O::T: no Β·C::A: yes - lazy attribute defaults β
C::T: yes Β·O::T: no Β·C::A: no - provides
newβC::T: yes Β·O::T: yes Β·C::A: yes - provides
DESTROYβC::T: yes Β·O::T: no Β·C::A: no newtakes either hashref or list βC::T: yes Β·O::T: no (list) Β·C::A: no (hash)- Moo(se)-like
BUILD/DEMOLISHβC::T: yes Β·O::T: no Β·C::A: no - Moo(se)-like
BUILDARGSβC::T: yes Β·O::T: no Β·C::A: no - no extraneous methods via
@ISAβC::T: yes Β·O::T: yes Β·C::A: no
Why this instead of Moose or Moo? π¦
Moose and Moo are both excellent OO frameworks, no cap. Moose offers a powerful meta-object protocol (MOP), but it's slow to start up and has about 30 non-core dependencies including XS modules. π Moo is faster to start up and has about 10 pure Perl dependencies, but provides no true MOP β it relies instead on its ability to transparently upgrade Moo to Moose when Moose's full feature set is required. slay for them, honestly.
By contrast, Class::Tiny has no MOP and has zero non-core dependencies for Perls in the support window. It has far less code, less complexity, and no learning curve. So if you don't need or can't afford what Moo or Moose offer, this is intended to be a reasonable fallback. π«Ά
That said, Class::Tiny does offer Moose-like conventions for things like BUILD and DEMOLISH for some minimal interoperability and an easier upgrade path. little sprinkle of compatibility, we love to see it. πΈ
π AUTHOR π
David Golden <dagolden@cpan.org>
π«Ά CONTRIBUTORS π«Ά
- Dagfinn Ilmari MannsΓ₯ker
<ilmari@ilmari.org> - David Golden
<xdg@xdg.me> - Gelu Lupas
<gelu@devnull.ro> - Karen Etheridge
<ether@cpan.org> - Matt S Trout
<mstrout@cpan.org> - Olivier MenguΓ©
<dolmen@cpan.org> - Toby Inkster
<tobyink@cpan.org>
the whole squad showed up, iconic. π
π COPYRIGHT AND LICENSE π
This software is Copyright (c) 2013 by David Golden.
This is free software, licensed under:
The Apache License, Version 2.0, January 2004
okay bestie that's the whole page, you're officially a Class::Tiny girlie now π
this was Class::Tiny(3) as shipped with perl v5.42.0, dated 2020-09-05 β go forth and make tiny little classes, mwah πβ¨
π¦ where this page comes from
- opensuse-leap 16.0: perl-Class-Tiny 1.008-160000.2.2 Β· Apache-2.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms