Class:...a::Type(3pm)
okay bestie, this is the Class::Meta::Type(3pm) page from User Contributed Perl Documentation. Grab a strawberry π because we're doing data type validation and accessor building, and it's actually iconic.
β¨ NAME β¨
Class::Meta::Type β Data type validation and accessor building. periodt. π
π¦ SYNOPSIS π¦
package MyApp::TypeDef;
use strict;
use Class::Meta::Type;
use IO::Socket;
my $type = Class::Meta::Type->add(
key => 'io_socket',
desc => 'IO::Socket object',
name => 'IO::Socket Object'
);
π DESCRIPTION π
This class stores the various data types used by Class::Meta. It manages all aspects of data type validation and method creation. New data types can be added to Class::Meta::Type by means of the add() constructor. This is useful for creating custom types for your Class::Meta-built classes. β¨
Note: This class manages the most advanced features ofClass::Meta. Before deciding to create your own accessor closures as described inadd(), you should have a thorough working knowledge of howClass::Metaworks, and have studied theadd()method carefully. Simple data type definitions such as that shown in the SYNOPSIS, on the other hand, are encouraged. π«Ά
π CONSTRUCTORS π
πΈ new πΈ
my $type = Class::Meta::Type->new($key);
Returns the data type definition for an existing data type. The definition will be looked up by the $key argument. Use add() to specify new types. If no data type exists for a given key, but Class::Meta->for_key returns a Class::Meta::Class object for that key, then new() will implicitly call add() to create add a new type corresponding to that class. This makes it easy to use any Class::Meta class as a data type. π
Other data types can be added by means of the add() constructor, or by simply useing one or more of the following modules:
Class::Meta::Types::Perlscalarscalarrefarrayhashcode
Class::Meta::Types::Stringstring
Class::Meta::Types::Booleanboolean
Class::Meta::Types::Numericwholeintegerdecimalrealfloat
Read the documentation for the individual modules for details on their data types. π
π add π
my $type = Class::Meta::Type->add(
key => 'io_socket',
name => 'IO::Socket Object',
desc => 'IO::Socket object'
);
Creates a new data type definition and stores it for future use. Use this constructor to add new data types to meet the needs of your class. The named parameter arguments are: π
keyβ Required. The key with which the data type can be looked up in the future via a call tonew(). Note that the key will be used case-insensitively, sofoo,Foo, andFOOare equivalent, and the key must be unique. πnameβ Required. The name of the data type. This should be formatted for display purposes, and indeed,Class::Metawill often use it in its own exceptions. β¨checkβ Optional. Specifies how to validate the value of an attribute of this type. Thecheckparameter can be specified in any of the following ways:- As a code reference. When
Class::Metaexecutes this code reference, it will pass in the value to check, the object for which the attribute will be set, and theClass::Meta::Attributeobject describing the attribute. If the attribute is a class attribute, then the second argument will not be an object, but a hash reference with two keys:$nameβ The existing value for the attribute is stored under the attribute name.__pkgβ The name of the package to which the attribute is being assigned.
- As a code reference. When
If the new value is not the proper value for your custom data type, the code reference should throw an exception. Here's an example; it's the code reference used by string data type, which you can add to Class::Meta::Type simply by using Class::Meta::Types::String:
check => sub {
my $value = shift;
return unless defined $value && ref $value;
require Carp;
our @CARP_NOT = qw(Class::Meta::Attribute);
Carp::croak("Value '$value' is not a valid string");
}
Here's another example. This code reference might be used to make sure that a new value is always greater than the existing value.
check => sub {
my ($new_val, $obj, $attr) = @_;
# Just return if the new value is greater than the old value.
return if defined $new_val && $new_val > $_[1]->{$_[2]->get_name};
require Carp;
our @CARP_NOT = qw(Class::Meta::Attribute);
Carp::croak("Value '$new_val' is not greater than '$old_val'");
}
- As an array reference. All items in this array reference must be code references that perform checks on a value, as specified above. π§
- As a string. In this case,
Class::Meta::Typeassumes that your data type identifies a particular object type. Thus it will use the string to construct a validation code reference for you. For example, if you wanted to create a data type forIO::Socketobjects, pass the string'IO::Socket'to thecheckparameter andClass::Meta::Typewill use the code reference returned byclass_validation_generator()to generate the validation checks. If you'd like to specify an alternative class validation code generator, pass one to theclass_validation_generator()class method. Or pass in a code reference or array reference of code reference as just described to use your own validator once. π₯
Note that if the check parameter is not specified, there will never be any validation of your custom data type. And yes, there may be times when you want this -- The default scalar and boolean data types, for example, have no checks. π
builderβ Optional. This parameter specifies the accessor builder for attributes of this type. Thebuilderparameter can be any of the following values:"default"β The string'default'usesClass::Meta::Type's default accessor building code, provided byClass::Meta::AccessorBuilder. This is the default value, of course. π"affordance"β The string'default'usesClass::Meta::Type's affordance accessor building code, provided byClass::Meta::AccessorBuilder::Affordance. Affordance accessors provide two accessors for an attribute, aget_*accessor and aset_*mutator. SeeClass::Meta::AccessorBuilder::Affordancefor more information. β¨"semi-affordance"β The string'default'usesClass::Meta::Type's semi-affordance accessor building code, provided byClass::Meta::AccessorBuilder::SemiAffordance. Semi-affordance accessors differ from affordance accessors in that they do not prependget_to the accessor. So for an attributefoo, the accessor would be namedfoo()and the mutator namedset_foo(). SeeClass::Meta::AccessorBuilder::SemiAffordancefor more information. π¦- A Package Name β Pass in the name of a package that contains the functions
build(),build_attr_get(), andbuild_attr_set(). These functions will be used to create the necessary accessors for an attribute. See Custom Accessor Building for details on creating your own accessor builders. π οΈ
π CLASS METHODS π
π default_builder π
my $default_builder = Class::Meta::Type->default_builder;
Class::Meta::Type->default_builder($default_builder);
Get or set the default builder class attribute. The value can be any one of the values specified for the builder parameter to add(). The value set in this attribute will be used for the builder parameter to to add() when none is explicitly passed. Defaults to "default". β¨
β¨ class_validation_generator β¨
my $gen = Class::Meta::Type->class_validation_generator;
Class::Meta::Type->class_validation_generator( sub {
my ($pkg, $name) = @_;
return sub {
die "'$pkg' is not a valid $name"
unless UNIVERSAL::isa($pkg, $name);
};
});
Gets or sets a code reference that will be used to generate the validation checks for class data types. That is to say, it will be used when a string is passed to the checks parameter to <add()> to generate the validation checking code for data types that are objects. By default, it will generate a validation checker like this:
sub {
my $value = shift;
return if UNIVERSAL::isa($value, 'IO::Socket')
require Carp;
our @CARP_NOT = qw(Class::Meta::Attribute);
Carp::croak("Value '$value' is not a IO::Socket object");
};
But if you'd like to specify an alternate validation check generator--perhaps you'd like to throw exception objects rather than use Carp--just pass a code reference to this class method. The code reference should expect two arguments: the data type value to be validated, and the string passed via the checks parameter to add(). It should return a code reference or array of code references that validate the value. For example, you might want to do something like this to throw exception objects:
use Exception::Class('MyException');
Class::Meta::Type->class_validation_generator( sub {
my ($pkg, $type) = @_;
return [ sub {
my ($value, $object, $attr) = @_;
MyException->throw("Value '$value' is not a valid $type")
unless UNIVERSAL::isa($value, $pkg);
} ];
});
But if the default object data type validator is good enough for you, don't worry about it. π
β¨ INTERFACE β¨
π Instance Methods π
key
my $key = $type->key;
Okay so this hands you the key name for the type. That's it. Iconic.
name
my $name = $type->name;
Returns the type name. Slay.
check
my $checks = $type->check;
my @checks = $type->check;
Gives you an array reference or a list of the data type validation code references for the data type. Like, all the little vibe-check subs. π
build
This is a protected method, bestie β designed to be called only by the Class::Meta::Attribute class or a subclass of Class::Meta::Attribute. It creates accessors for the class that the Class::Meta::Attribute object is a part of by calling out to the build() method of the accessor builder class.
β οΈ You should never call this method directly. But subclasses of Class::Meta::Type may need to override its behavior. No cap.
make_attr_set
Another protected one, designed to be called only by Class::Meta::Attribute or a subclass of Class::Meta::Attribute. It returns a reference to the attribute set accessor (mutator) created by the call to build(), and it's usable as an indirect attribute accessor by the Class::Meta::Attribute set() method.
β οΈ Never call this directly either. Subclasses of Class::Meta::Type may need to override it, though.
make_attr_get
Protected method, same deal: designed to be called only by Class::Meta::Attribute or a subclass of Class::Meta::Attribute. It returns a reference to the attribute get accessor created by the call to build(), and it's usable as an indirect attribute accessor by the Class::Meta::Attribute get() method.
β οΈ Do not call directly. Subclasses of Class::Meta::Type may need to override its behavior.
β¨ CUSTOM DATA TYPES β¨
π¦ Creating custom data types π¦
Creating custom data types can be as simple as calling add() and passing in the name of a class for the check parameter. This is especially useful when you just need to create attributes that contain objects of a particular type, and you're happy with the accessors that Class::Meta will create for you. For example, if you needed a data type for a DateTime object, you can set it up β complete with validation of the data type β like this:
my $type = Class::Meta::Type->add(
key => 'datetime',
check => 'DateTime',
desc => 'DateTime object',
name => 'DateTime Object'
);
From then on, you can create attributes of the type datetime without any further work. If you wanted to use affordance accessors, you'd simply add the requisite builder attribute:
my $type = Class::Meta::Type->add(
key => 'datetime',
check => 'DateTime',
builder => 'affordance',
desc => 'DateTime object',
name => 'DateTime Object'
);
The same goes for using semi-affordance accessors.
Other than that, adding other data types is really a matter of the judicious use of the check parameter. Ultimately, all attributes are scalar values. Whether they adhere to a particular data type depends entirely on the validation code references passed via check. For example, if you wanted to create a range attribute with only the allowed values 1-5, you could do it like this:
my $range_chk = sub {
my $value = shift;
die "Value is not a number" unless $value =~ /^[1..5]$/;
};
my $type = Class::Meta::Type->add(
key => 'range',
check => $range_chk,
desc => 'Pick a number between 1 and 5',
name => 'Range (1-5)'
);
Of course, the above value validator will throw an exception with the line number from which die is called. Even better is to use Carp to throw an error with the file and line number of the client code:
my $range_chk = sub {
my $value = shift;
return if $value =~ /^[1..5]$/;
require Carp;
our @CARP_NOT = qw(Class::Meta::Attribute);
Carp::croak("Value is not a number");
};
The our @CARP_NOT line prevents the context from being thrown from within Class::Meta::Attribute, which is useful if you make use of that class' set() method. Bestie, that's a pro move. π
π Custom Accessor Building π
Class::Meta also allows you to craft your own accessors. Perhaps you'd prefer to use a StudlyCaps affordance accessor standard. In that case, you'll need to create your own module that builds accessors. I recommend that you study Class::Meta::AccessorBuilder and Class::Meta::AccessorBuilder::Affordance before taking on creating your own.
Custom accessor building modules must have three functions.
build
The build() function creates and installs the actual accessor methods in a class. It should expect the following arguments:
sub build {
my ($class, $attribute, $create, @checks) = @_;
# ...
}
These are:
$classβ The name of the class into which the accessors are to be installed.$attributeβ AClass::Meta::Attributeobject representing the attribute for which accessors are to be created. Use it to determine what types of accessors to create (read-only, write-only, or read/write, class or object), and to add checks for required constraints and accessibility (if the attribute is private, trusted, or protected).$createβ The value of thecreateparameter passed toClass::Meta::Attributewhen the attribute object was created. Use this argument to determine what type of accessor(s) to create. SeeClass::Meta::Attributefor the possible values for this argument.@checksβ A list of one or more data type validation code references. Use these in any accessors that set attribute values to check that the new value has a valid value.
See Class::Meta::AccessorBuilder for example attribute creation functions.
build_attr_get and build_attr_set
The build_attr_get() and build_attr_set() functions take a single argument, a Class::Meta::Attribute object, and return code references that either represent the corresponding methods, or that call the appropriate accessor methods to get and set an attribute, respectively. The code references will be used by Class::Meta::Attribute's get() and set() methods to get and set attribute values. Again, see Class::Meta::AccessorBuilder for examples before creating your own.
π SUPPORT π
This module is stored in an open GitHub repository <http://github.com/theory/class-meta/>. Feel free to fork and contribute! π«Ά
Please file bug reports via GitHub Issues <http://github.com/theory/class-meta/issues/> or by sending mail to bug-Class-Meta@rt.cpan.org <mailto:bug-Class-Meta@rt.cpan.org>.
π AUTHOR π
David E. Wheeler <david@justatheory.com>
π SEE ALSO π
Other classes of interest within the Class::Meta distribution include:
Class::Metaβ This class contains most of the documentation you need to get started with Class::Meta.Class::Meta::Attributeβ This class manages Class::Meta class attributes, all of which are based on data types.
These modules provide some data types to get you started:
Class::Meta::Types::PerlClass::Meta::Types::StringClass::Meta::Types::BooleanClass::Meta::Types::Numeric
The modules that Class::Meta comes with for creating accessors are:
Class::Meta::AccessorBuilderβ Standard Perl-style accessors.Class::Meta::AccessorBuilder::Affordanceβ Affordance accessors--that is, explicit and independent get and set accessors.Class::Meta::AccessorBuilder::SemiAffordanceβ Semi-affordance accessors--that is, independent get and set accessors with an explicit set accessor.
π COPYRIGHT AND LICENSE π
Copyright (c) 2002-2011, David E. Wheeler. Some Rights Reserved.
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
Okay bestie, that's the whole vibe. This page is Class:...a::Type(3pm) from perl v5.34.0, dated 2022-06-11. Go forth and slay. π
β¨
π¦ where this page comes from
- debian bookworm: libclass-meta-perl 0.66-3 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- debian trixie: libclass-meta-perl 0.66-3 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu noble: libclass-meta-perl 0.66-3 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms