| Class::Meta - Class automation, introspection, and data validation |
Class::Meta - Class automation, introspection, and data validation
Generate a class:
package MyApp::Thingy; use strict; use Class::Meta; use Class::Meta::Types::String; use Class::Meta::Types::Numeric;
BEGIN {
# Create a Class::Meta object for this class.
my $cm = Class::Meta->new( key => 'thingy' );
# Add a constructor.
$cm->add_constructor(
name => 'new',
create => 1,
);
# Add a couple of attributes with generated methods.
$cm->add_attribute(
name => 'uuid',
authz => Class::Meta::READ,
type => 'string',
required => 1,
default => sub { Data::UUID->new->create_str },
);
$cm->add_attribute(
name => 'name',
is => 'string',
required => 1,
default => undef,
);
$cm->add_attribute(
name => 'age',
is => 'integer',
default => undef,
);
# Add a custom method.
$cm->add_method(
name => 'chk_pass',
view => Class::Meta::PUBLIC,
);
$cm->build;
}
Then use the class:
use MyApp::Thingy;
my $thingy = MyApp::Thingy->new; print "ID: ", $thingy->id, $/; $thingy->name('Larry'); print "Name: ", $thingy->name, $/; $thingy->age(42); print "Age: ", $thingy->age, $/;
Or make use of the introspection API:
use MyApp::Thingy;
my $class = MyApp::Thingy->my_class; my $thingy;
print "Examining object of class ", $class->package, $/;
print "\nConstructors:\n"; for my $ctor ($class->constructors) { print " o ", $ctor->name, $/; $thingy = $ctor->call($class->package); }
print "\nAttributes:\n"; for my $attr ($class->attributes) { print " o ", $attr->name, " => ", $attr->get($thingy), $/; if ($attr->authz >= Class::Meta::SET && $attr->type eq 'string') { $attr->get($thingy, 'hey there!'); print " Changed to: ", $attr->get($thingy), $/; } }
print "\nMethods:\n"; for my $meth ($class->methods) { print " o ", $meth->name, $/; $meth->call($thingy); }
Class::Meta provides an interface for automating the creation of Perl classes with attribute data type validation. It differs from other such modules in that it includes an introspection API that can be used as a unified interface for all Class::Meta-generated classes. In this sense, it is an implementation of the "Facade" design pattern.
One might argue that there are already too many class automation and parameter validation modules on CPAN. And one would be right. They range from simple accessor generators, such as Class::Accessor, to simple parameter validators, such as Params::Validate, to more comprehensive systems, such as Class::Contract and Class::Tangram. But, naturally, none of them could do exactly what I needed.
What I needed was an implementation of the "Facade" design pattern. Okay, this isn't a facade like the GOF meant it, but it is in the respect that it creates classes with a common API so that objects of these classes can all be used identically, calling the same methods on each. This is done via the implementation of an introspection API. So the process of creating classes with Class::Meta not only creates attributes and accessors, but also creates objects that describe those classes. Using these descriptive objects, client applications can determine what to do with objects of Class::Meta-generated classes. This is particularly useful for user interface code.
Before we get to the introspection API, let's take a look at how to create classes with Class::Meta. Unlike many class automation modules for Perl, the classes that Class::Meta builds do not inherit from Class::Meta. This frees you from any dependencies on the interfaces that such a base class might compel. For example, you can create whatever constructors you like, and name them whatever you like.
I recommend that you create your Class::Meta classes in a BEGIN
block. Although this is not strictly necessary, it helps to ensure that the
classes you're building are completely constructed and ready to go by the time
compilation has completed. Creating classes with Class::Meta is easy, using
the Class::Meta object oriented interface. Here is an example of a very simple
class:
package MyApp::Dog; use strict; use Class::Meta; use Class::Meta::Types::Perl;
BEGIN {
# Create a Class::Meta object for this class.
my $cm = Class::Meta->new( key => 'dog' );
# Add a constructor.
$cm->add_constructor(
name => 'new',
create => 1,
);
# Add an attribute.
$cm->add_attribute(
name => 'tail',
type => 'scalar',
);
# Add a custom method.
$cm->add_method( name => 'wag' );
$cm->build;
}
sub wag { my $self = shift; print "Wagging ", $self->tail; }
This simple example shows of the construction of all three types of objects supported by Class::Meta: constructors, attributes, and methods. Here's how it does it:
First we load Class::Meta and Class::Meta::Types::Perl. The latter module creates data types that can be used for attributes, including a "scalar" data type.
Second, we create a Class::Meta object. It's okay to create it within the
BEGIN block, as it won't be needed beyond that. All Class::Meta classes
have a key that uniquely identifies them across an application. If none is
provided, the class name will be used, instead.
Next, we create a Class::Meta::Constructor object to describe a constructor
method for the class. The create parameter to the add_constructor() method
tells Class::Meta to create the constructor named "new()".
Then we call add_attribute() to create a single attribute, "tail". This is a
simple scalar attribute, meaning that any scalar value can be stored in
it. Class::Meta will create a Class::Meta::Attribute object that describes
this attribute, and will also shortly create accessor methods for the
attribute.
The add_method() method constructs a Class::Meta::Method object to describe
any methods written for the class. In this case, we've told Class::Meta that
there will be a wag() method.
And finally, we tell Class::Meta to build the class. This is the point at
which all constructors and accessor methods will be created in the class. In
this case, these include the new() constructor and a tail() accessor for
the "tail" attribute. And finally, Class::Meta will install another method,
my_class(). This method will return a Class::Meta::Class object that
describes the class, and provides the complete introspection API.
Thus, the class the above code creates has this interface:
sub my_class; sub new; sub tail; sub wag;
By default, Class::Meta loads no data types. If you attempt to create an attribute without creating or loading the appropriate data type, you will get an error.
But I didn't want to leave you out in the cold, so I created a whole bunch of
data types to get you started. Any of these will automatically be loaded by
Class::Meta if it is used to create an attribute. They can also be loaded
simply by useing the appropriate module. The modules are:
Typical Perl data types.
Any scalar value.
A scalar reference.
An array reference.
A hash reference.
A code reference.
Attributes of this type must contain a string value. Essentially, this means anything other than a reference.
Attributes of this type store a boolean value. Implementation-wise, this means either a 1 or a 0.
These data types are validated by the functions provided by Data::Types.
A whole number.
An integer.
A decimal number.
A real number.
a floating point number.
Other data types may be added in the future. See the individual data type modules for more information.
Class::Meta supports the creation of three different types of attribute accessors: typical Perl single-method accessors, "affordance" accessors, and "semi-affordance" accessors. The single accessors are named for their attributes, and typically tend to look like this:
sub tail { my $self = shift; return $self->{tail} unless @_; return $self->{tail} = shift; }
Although this can be an oversimplification if the data type has associated validation checks.
Affordance accessors provide at up to two accessors for every attribute: One to set the value and one to retrieve the value. They tend to look like this:
sub get_tail { shift->{tail} }
sub set_tail { shift->{tail} = shift }
These accessors offer a bit less overhead than the traditional Perl accessors, in that they don't have to check whether they're called to get or set a value. They also have the benefit of creating a psychological barrier to misuse. Since traditional Perl accessors can be created as read-only or write-only accessors, one can't tell just by looking at them which is the case. The affordance accessors make this point moot, as they make clear what their purpose is.
Semi-affordance accessors are similar to affordance accessors in that they provide at least two accessors for every attribute. However, the accessor that fetches the value is named for the attribute. Thus, they tend to look like this:
sub tail { shift->{tail} }
sub set_tail { shift->{tail} = shift }
To get Class::Meta's data types to create affordance accessors, simply pass the string "affordance" to them when you load them:
use Class::Meta::Types::Perl 'affordance';
Likewise, to get them to create semi-affordance accessors, pass the string "semi-affordance":
use Class::Meta::Types::Perl 'semi-affordance';
The boolean data type is the only one that uses a slightly different approach to the creation of affordance accessors: It creates three of them. Assuming you're creating a boolean attribute named "alive", it will create these accessors:
sub is_alive { shift->{alive} } sub set_alive_on { shift->{alive} = 1 } sub set_alive_off { shift->{alive} = 0 }
Incidentally, I stole the term "affordance" from Damian Conway's "Object Oriented Perl," pp 83-84, where he borrows it from Donald Norman.
See Class::Meta::Type for details on creating new data types.
Class::Meta provides four classes the make up the introspection API for Class::Meta-generated classes. Those classes are:
Describes the class. Each Class::Meta-generated class has a single constructor
object that can be retrieved by calling a class' my_class() class
method. Using the Class::Meta::Class object, you can get access to all of the
other objects that describe the class. The relevant methods are:
Provides access to all of the Class::Meta::Constructor objects that describe the class' constructors, and provide indirect access to those constructors.
Provides access to all of the Class::Meta::Attribute objects that describe the class' attributes, and provide methods for indirectly getting and setting their values.
Provides access to all of the Class::Meta::Method objects that describe the class' methods, and provide indirect execution of those constructors.
Describes a class constructor. Typically a class will have only a single constructor, but there could be more, and client code doesn't necessarily know its name. Class::Meta::Constructor objects resolve these issues by describing all of the constructors in a class. The most useful methods are:
Returns the name of the constructor, such as "new".
Calls the constructor on an object, passing in the arguments passed to
call() itself.
Describes a class attribute, including its name and data type. Attribute objects are perhaps the most useful Class::Meta objects, in that they can provide a great deal of information about the structure of a class. The most interesting methods are:
Returns the name of the attribute.
Returns the name of the attribute's data type.
Returns true if the attribute is required to have a value.
Returns true if the attribute value can be set to a defined value only once.
Sets the value of an attribute on an object.
Returns the value of an attribute on an object.
Describes a method of a class, including its name and context (class vs. instance). The relevant methods are:
The method name.
The context of the method indicated by a value corresponding to either Class::Meta::OBJECT or Class::Meta::CLASS.
Calls the method, passing in the arguments passed to call() itself.
Consult the documentation of the individual classes for a complete description of their interfaces.
Class::Meta->default_error_handler($code); my $default_error_handler = Class::Meta->default_error_handler;
Sets the default error handler for Class::Meta classes. If no error_handler
attribute is passed to new, then this error handler will be associated with
the new class. The default default error handler uses Carp::croak() to
handle errors.
Note that if other modules are using Class::Meta that they will use your default error handler unless you reset the default error handler to its original value before loading them.
Class::Meta->handle_error($err);
Uses the code reference returned by default_error_handler() to handle an
error. Used internally Class::Meta classes when no Class::Meta::Class object
is available. Probably not useful outside of Class::Meta unless you're
creating your own accessor generation class. Use the handle_error()
instance method in Class::Meta::Class, instead.
my $class = Class::Meta->for_key($key);
Returns the Class::Meta::Class object for a class by its key name. This can be
useful in circumstances where the key has been used to track a class, and you
need to get a handle on that class. With the class package name, you can of
course simply call $pkg->my_class; this method is the solution for
getting the class object for a class key.
my @keys = Class::Meta->keys;
Returns the keys for all Class::Meta::Class objects. The order of keys is not guaranteed. In scalar context, this method returns an array reference containing the keys.
Class::Meta->clear; Class::Meta->clear($key);
Called without arguments, clear will remove all
Class::Meta::Class objects from memory. Called with an
argument, clear attempts to remove only that key from memory. Calling it
with a non-existent key is a no-op.
In general, you probably won't want to use this method, except perhaps in tests, when you might need to do funky things with your classes.
my $cm = Class::Meta->new( key => $key );
Constructs and returns a new Class::Meta object that can then be used to define and build the complete interface of a class. The supported parameters are:
The package that defines the class. Defaults to the package of the code
that calls new().
A key name that uniquely identifies a class within an application. Defaults to
the value of the package parameter if not specified.
A boolean indicating whether the class being defined is an abstract class. An abstract class, also known as a "virtual" class, is not intended to be used directly. No objects of an abstract class should every be created. Instead, classes that inherit from an abstract class must be implemented.
An array reference of key names or packages that are trusted by the class.
trust => ['Foo::Bar', 'Foo::Bat'],
Trusted packages and the classes that inherit from them can retrieve trusted attributes and methods of the class. Trusted packages need not be Class::Meta classes. Trusted classes do not include the declaring class by default, so if you want the class that declares an attribute to be able to use trusted attribute accessors, be sure to include it in the list of trusted packages:
trust => [__PACKAGE__, 'Foo::Bar', 'Foo::Bat'],
If you need to trust a single class, you may pass in the key name or package of that class rather than an array reference:
trust => 'Foo::Bar',
The name of a class that inherits from Class::Meta::Class to be used to create all of the class objects for the class. Defaults to Class::Meta::Class.
The name of a class that inherits from Class::Meta::Constructor to be used to create all of the constructor objects for the class. Defaults to Class::Meta::Constructor.
The name of a class that inherits from Class::Meta::Attribute to be used to create all of the attribute objects for the class. Defaults to Class::Meta::Attribute.
The name of a class that inherits from Class::Meta::Method to be used to create all of the method objects for the class. Defaults to Class::Meta::Method.
A code reference that will be used to handle errors thrown by the methods
created for the new class. Defaults to the value returned by
Class::Meta->default_error_handler.
$cm->add_constructor( name => 'construct', create => 1, );
Creates and returns a Class::Meta::Constructor object that describes a constructor for the class. The supported parameters are:
The name of the constructor. The name must consist of only alphanumeric characters or "_". Required.
When true, Class::Meta::Constructor will automatically create and install a
constructor named for the name parameter. Defaults to true unless code
is passed. In general you won't need to specify this parameter unless you've
written your own constructor in the package, in which case you'll want to
specify create => 0.
A label for the constructor. Generally used for displaying its name in a user interface. Optional.
A description of the constructor. Possibly useful for displaying help text in a user interface. Optional.
You can implicitly define the constructor in your class by passing a code
reference via the code parameter. Once build() is called,
Kinetic::Meta::Constructor will install the
constructor into the package for which the Class::Meta object was defined, and
with the name specified via the name parameter. Note that if the
constructor view is PRIVATE or PROTECTED, the constructor will be wrapped in
extra code to envocde the view. Optional.
The visibility of the constructor. The possible values are defined by the following constants:
Can be used by any client.
Can only be used by the declaring class.
Can only be used by the classes specified by the trust parameter to
new().
Can only be used by the declaring class or by classes that inherit from it.
Defaults to Class::Meta::PUBLIC if not defined.
A code reference that calls the constructor. Defaults to a code reference that
calls a method with the name provided by the name attribute on the class
being defined.
$cm->add_attribute( name => 'tail', type => 'scalar', );
Creates and returns a Class::Meta::Attribute object that describes an attribute of the class. The supported parameters are:
The name of the attribute. The name must consist of only alphanumeric characters or "_". Required.
The data type of the attribute. See Data Types for some possible values
for this parameter. If the type name corresponds to a data type in a package
in the Class::Meta::Types namespae, that package will automatically be loaded
and configured with Perl-style accessors, so that the data type can simply be
used. Required. If both type and is are passed, is will be used.
A boolean value indicating whether the attribute is required to have a value. Defaults to false.
A boolean value indicating whether the attribute can be set to a defined value only once. Defaults to false.
A label for the attribute. Generally used for displaying its name in a user interface. Optional.
A description of the attribute. Possibly useful for displaying help text in a user interface. Optional.
The visibility of the attribute. See the description of the view parameter
to add_constructor for a description of its value.
The authorization of the attribute. This value indicates whether it is read-only, write-only, read/write, or inaccessible. The possible values are defined by the following constants:
Defaults to Class::Meta::RDWR if not defined.
Indicates what type of accessor or accessors are to be created for the attribute.
Create read-only accessor(s).
Create write-only accessor(s).
Create read/write accessor(s).
Create no accessors.
If not unspecified, the value of the create parameter will correspond to
the value of the authz parameter like so:
authz create ------------------ READ => GET WRITE => SET RDWR => GETSET NONE => NONE
The create parameter differs from the authz parameter in case you've
taken it upon yourself to create some accessors, and therefore don't need
Class::Meta to do so. For example, if you were using standard Perl-style
accessors, and needed to do something a little different by coding your own
accessor, you'd specify it like this:
$cm->add_attribute( name => $name, type => $type, authz => Class::Meta::RDWR, create => Class::Meta::NONE );
Just be sure that your custom accessor compiles before you call
$cm->build so that Class::Meta::Attribute can get a handle on it for
its get() and/or set() methods.
The context of the attribute. This indicates whether it's a class attribute or an object attribute. The possible values are defined by the following constants:
The default value for the attribute, if any. This may be either a literal value or a code reference that will be executed to generate a default value.
If an attribute being added to a class has the same name as an attribute in a
parent class, Class::Meta will normally throw an exception. However, in some
cases you might want to override an attribute in a parent class to change its
properties. In such a case, pass a true value to the override parameter to
override the attribute and avoid the exception.
$cm->add_method( name => 'wag' );
Creates and returns a Class::Meta::Method object that describes a method of the class. The supported parameters are:
The name of the method. The name must consist of only alphanumeric characters or "_".
A label for the method. Generally used for displaying its name in a user interface. Optional.
A description of the method. Possibly useful for displaying help text in a user interface. Optional.
The visibility of the method. See the description of the view parameter to
add_constructor for a description of its value.
You can implicitly define the method in your class by passing a code reference
via the code parameter. Once build() is called,
Kinetic::Meta::Method will install the method into
the package for which the Class::Meta object was defined, and with the name
specified via the name parameter.
The context of the method. This indicates whether it's a class method or an
object method. See the description of the context parameter to add_attribute
for a description of its value.
A code reference that calls the method. This code reference will be be used by
the call() method of Class::Meta::Method to execute
the method on behalf of an object. Defaults to a code reference that calls a
method with the name provided by the name attribute on the class being
defined.
A description of the arguments to the method. This can be anything you like, but I recommend something like a string for a single argument, an array reference for a list of arguments, or a hash reference for parameter arguments.
A string describing the return value or values of the method.
my $class = $cm->class;
Returns the instance of the Class::Meta::Class object that will be used to provide the introspection API for the class being generated.
$cm->build;
Builds the class defined by the Class::Meta object, including the
my_class() class method, and all requisite constructors and accessors.
Make class attribute accessors behave as they do in Class::Data::Inheritable.
Modify class attribute accessors so that they are thread safe. This will involve sharing the attributes across threads, and locking them before changing their values. If they've also been made to behave as they do in Class::Data::Inheritable, we'll have to figure out a way to make it so that newly generated accessors for subclasses are shared between threads, too. This may not be easy.
Please send bug reports to <bug-class-meta@rt.cpan.org> or report them via the CPAN Request Tracker at http://rt.cpan.org/NoAuth/Bugs.html.
David Wheeler <david@kineticode.com>
Other classes of interest within the Class::Meta distribution include:
For comparative purposes, you might also want to check out these fine modules:
Accessor and constructor automation.
Parameter validation.
Design by contract.
Accessor automation and data validation for Tangram applications.
An ambitious yet underdocumented module that also manages accessor and constructor generation, data validation, and provides a reflection API. It also supports serialization.
Stevan Little's application of Perl 6 meta classes to Perl 5.
"It's the new camel." Another extention of the Perl 5 object system, built on Class::MOP.
Copyright (c) 2002-2006, David Wheeler. All Rights Reserved.
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
| Class::Meta - Class automation, introspection, and data validation |