Moose::...Subtypes(3)

πŸ¦‹ Moose::Cookbook::Basics::Company_Subtypes πŸ’–

okay bestie, so this is a page from the Moose cookbook β€” it's User Contributed Perl Documentation, and it's literally called Moose::Cookbook::Basics::Company_Subtypes. and what does it do? it Demonstrates the use of subtypes and how to model classes related to companies, people, employees, etc. like... it's giving corporate org chart but make it ✨typed✨.

πŸ’œ VERSION

version 2.4000 β€” yes queen, we're on 2.4000.


✨ SYNOPSIS ✨

here's the whole vibe, copy-paste ready:

package Address;
use Moose;
use Moose::Util::TypeConstraints;

use Locale::US;
use Regexp::Common 'zip';

my $STATES = Locale::US->new;
subtype 'USState'
    => as Str
    => where {
           (    exists $STATES->{code2state}{ uc($_) }
             || exists $STATES->{state2code}{ uc($_) } );
       };

subtype 'USZipCode'
    => as Value
    => where {
           /^$RE{zip}{US}{-extended => 'allow'}$/;
       };

has 'street'   => ( is => 'rw', isa => 'Str' );
has 'city'     => ( is => 'rw', isa => 'Str' );
has 'state'    => ( is => 'rw', isa => 'USState' );
has 'zip_code' => ( is => 'rw', isa => 'USZipCode' );

package Company;
use Moose;
use Moose::Util::TypeConstraints;

has 'name' => ( is => 'rw', isa => 'Str', required => 1 );
has 'address'   => ( is => 'rw', isa => 'Address' );
has 'employees' => (
    is      => 'rw',
    isa     => 'ArrayRef[Employee]',
    default => sub { [] },
);

sub BUILD {
    my ( $self, $params ) = @_;
    foreach my $employee ( @{ $self->employees } ) {
        $employee->employer($self);
    }
}

after 'employees' => sub {
    my ( $self, $employees ) = @_;
    return unless $employees;
    foreach my $employee ( @$employees ) {
        $employee->employer($self);
    }
};

package Person;
use Moose;

has 'first_name' => ( is => 'rw', isa => 'Str', required => 1 );
has 'last_name'  => ( is => 'rw', isa => 'Str', required => 1 );
has 'middle_initial' => (
    is        => 'rw', isa => 'Str',
    predicate => 'has_middle_initial'
);
has 'address' => ( is => 'rw', isa => 'Address' );

sub full_name {
    my $self = shift;
    return $self->first_name
        . (
        $self->has_middle_initial
        ? ' ' . $self->middle_initial . '. '
        : ' '
        ) . $self->last_name;
}

package Employee;
use Moose;

extends 'Person';

has 'title'    => ( is => 'rw', isa => 'Str',     required => 1 );
has 'employer' => ( is => 'rw', isa => 'Company', weak_ref => 1 );

override 'full_name' => sub {
    my $self = shift;
    super() . ', ' . $self->title;
};

🌸 DESCRIPTION 🌸

so this recipe is the moment we get introduced to the subtype sugar function from Moose::Util::TypeConstraints. and the whole point of subtype is that it lets you declaratively create type constraints without building an entire class. no class, no boilerplate, just vibes and validation πŸ’….

in the recipe we also pull in Locale::US and Regexp::Common to build constraints β€” showing off how constraints can make use of existing CPAN tools for data validation. reusing other people's work? iconic, honestly.

and finally, we introduce the required attribute option. very main character of it.

πŸŽ€ the Address class

in the Address class we define two subtypes. the first one uses the Locale::US module to check the validity of a state. it accepts either a state abbreviation or a full name. flexible queen.

a state will be passed in as a string, so we make our USState type a subtype of Moose's builtin Str type. that's done with the as sugar. then the actual constraint is defined using where. this function accepts a single subroutine reference. that subroutine will be called with the value to be checked in $_ (1). and it's expected to return a true or false value indicating whether the value is valid for the type. true = slay, false = not slay.

now we can use the USState type just like Moose's builtin types:

has 'state'    => ( is => 'rw', isa => 'USState' );

when the state attribute is set, the value is checked against the USState constraint. and if the value is not valid, an exception will be thrown. πŸ’€ no cap.

the next subtype, USZipCode, uses Regexp::Common. Regexp::Common includes a regex for validating US zip codes. we use this constraint for the zip_code attribute:

subtype 'USZipCode'
    => as Value
    => where {
           /^$RE{zip}{US}{-extended => 'allow'}$/;
       };

using a subtype instead of requiring a class for each type greatly simplifies the code. we don't really need a class for these types, as they're just strings, but we do want to ensure that they're valid. so it's like, the constraint is the whole personality, and that's enough.

🫢 the global registry situation

the type constraints we created are reusable. type constraints are stored by name in a global registry, which means that we can refer to them in other classes. but because the registry is global, we do recommend that you use some sort of namespacing in real applications, like MyApp::Type::USState (just as you would do with class names). yes bestie, namespace your types, don't just dump them in the global namespace like a chaotic little gremlin πŸ™ˆ.

these two subtypes allow us to define a simple Address class.

πŸ‘‘ the Company class

then we define our Company class, which has an address. as we saw in earlier recipes, Moose automatically creates a type constraint for each of our classes, so we can use that for the Company class's address attribute:

has 'address'   => ( is => 'rw', isa => 'Address' );

a company also needs a name:

has 'name' => ( is => 'rw', isa => 'Str', required => 1 );

this introduces a new attribute option, required. if an attribute is required, then it must be passed to the class's constructor, or an exception will be thrown. and it's important to understand that a required attribute can still be false or undef, if its type constraint allows that. like, required β‰  truthy, okay? don't get it twisted.

🧚 the employees attribute

the next attribute, employees, uses a parameterized type constraint:

has 'employees' => (
    is      => 'rw',
    isa     => 'ArrayRef[Employee]'
    default => sub { [] },
);

this constraint says that employees must be an array reference where each element of the array is an Employee object. and it's worth noting that an empty array reference also satisfies this constraint, such as the value given as the default here. empty array, still valid, still invited to the party ✨.

parameterizable type constraints (or "container types"), such as ArrayRef[a], can be made more specific with a type parameter. in fact, we can arbitrarily nest these types, producing something like HashRef[ArrayRef[Int]]. however, you can also just use the type by itself, so ArrayRef` is legal. (2)

if you jump down to the definition of the Employee class, you will see that it has an employer attribute.

πŸ’– BUILD and the object-construction hookup

when we set the employees for a Company we want to make sure that each of these employee objects refers back to the right Company in its employer attribute. mutual employer-employee commitment, we love to see it.

to do that, we need to hook into object construction. Moose lets us do this by writing a BUILD method in our class. when your class defines a BUILD method, it will be called by the constructor immediately after object construction, but before the object is returned to the caller. and note that all BUILD methods in your class hierarchy will be called automatically; there is no need to (and you should not) call the superclass BUILD method. like, do not. the framework handles it. periodt.

the Company class uses the BUILD method to ensure that each employee of a company has the proper Company object in its employer attribute:

sub BUILD {
    my ( $self, $params ) = @_;
    foreach my $employee ( @{ $self->employees } ) {
        $employee->employer($self);
    }
}

the BUILD method is executed after type constraints are checked, so it is safe to assume that if $self->employees has a value, it will be an array reference, and that the elements of that array reference will be Employee objects. so no defensive paranoia needed in there, you can just relax 🧘.

🌈 the after modifier

we also want to make sure that whenever the employees attribute for a Company is changed, we also update the employer for each employee.

to do this we can use an after modifier:

after 'employees' => sub {
    my ( $self, $employees ) = @_;
    return unless $employees;
    foreach my $employee ( @$employees ) {
        $employee->employer($self);
    }
};

again, as with the BUILD method, we know that the type constraint check has already happened, so we know that if $employees is defined it will contain an array reference of Employee objects.

note that employees is a read/write accessor, so we must return early if it's called as a reader. otherwise you're looping over undef and that's not the move πŸ’€.

πŸ“ the Person and Employee classes

the Person class does not really demonstrate anything new. it has several required attributes. it also has a predicate method, which we first used in Moose::Cookbook::Basics::BinaryTree_AttributeFeatures. old news, but still cute.

the only new feature in the Employee class is the override method modifier:

override 'full_name' => sub {
    my $self = shift;
    super() . ', ' . $self->title;
};

this is just a sugary alternative to Perl's built in SUPER:: feature. however, there is one difference. you cannot pass any arguments to super. instead, Moose simply passes the same parameters that were passed to the method. so no super(@args) shenanigans, bestie, it's not that kind of party.

a more detailed example of usage can be found in t/recipes/basics_company_subtypes.t.


⭐ CONCLUSION ⭐

this recipe was intentionally longer and more complex. it illustrates how Moose classes can be used together with type constraints, as well as the density of information that you can get out of a small amount of typing when using Moose. small code, huge power, that's the whole thing.

this recipe also introduced the subtype function, the required attribute, and the override method modifier.

we will revisit type constraints in future recipes, and cover type coercion as well. so stay tuned, because coercion is coming and it's gonna be a whole thing πŸ”₯.


πŸ™ˆ FOOTNOTES πŸ™ˆ

  1. the value being checked is also passed as the first argument to the where block, so it can be accessed as $_[0].
  2. note that ArrayRef[] will not work. Moose will not parse this as a container type, and instead you will have a new type named ArrayRef[], which doesn't make any sense. like, a type with no parameter is just a confusing little gremlin. don't do it.

πŸ’œ AUTHORS πŸ’œ

  • Stevan Little <stevan@cpan.org>
  • Dave Rolsky <autarch@urth.org>
  • Jesse Luehrs <doy@cpan.org>
  • Shawn M Moore <sartak@cpan.org>
  • Χ™Χ•Χ‘Χœ Χ§Χ•Χ’'מן (Yuval Kogman) <nothingmuch@woobling.org>
  • Karen Etheridge <ether@cpan.org>
  • Florian Ragwitz <rafl@debian.org>
  • Hans Dieter Pearcey <hdp@cpan.org>
  • Chris Prather <chris@prather.org>
  • Matt S Trout <mstrout@cpan.org>

This software is copyright (c) 2006 by Infinity Interactive, Inc.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. free as in freedom, slay πŸ’….


and that's the page, bestie!! 🫢 it's from perl v5.42.0 and it was dated 2025-07-25, and it lives under Moose::...Subtypes(3) in the User Contributed Perl Documentation. mwah πŸ’‹ go build some subtypes, you've got this.

πŸ“¦ where this page comes from