NAME

Class::MOP::Class - Class Meta Object

SYNOPSIS

# assuming that class Foo
# has been defined, you can

# use this for introspection ...

# add a method to Foo ...
Foo->meta->add_method('bar' => sub { ... })

# get a list of all the classes searched
# the method dispatcher in the correct order
Foo->meta->class_precedence_list()

# remove a method from Foo
Foo->meta->remove_method('bar');

# or use this to actually create classes ...

Class::MOP::Class->create('Bar' => (
    version      => '0.01',
    superclasses => [ 'Foo' ],
    attributes => [
        Class::MOP:::Attribute->new('$bar'),
        Class::MOP:::Attribute->new('$baz'),
    ],
    methods => {
        calculate_bar => sub { ... },
        construct_baz => sub { ... }
    }
));

DESCRIPTION

This is the largest and currently most complex part of the Perl 5 meta-object protocol. It controls the introspection and manipulation of Perl 5 classes (and it can create them too). The best way to understand what this module can do, is to read the documentation for each of it's methods.

METHODS

Self Introspection

meta

This will return a Class::MOP::Class instance which is related to this class. Thereby allowing Class::MOP::Class to actually introspect itself.

As with Class::MOP::Attribute, Class::MOP will actually bootstrap this module by installing a number of attribute meta-objects into it's metaclass. This will allow this class to reap all the benifits of the MOP when subclassing it.

Class construction

These methods will handle creating Class::MOP::Class objects, which can be used to both create new classes, and analyze pre-existing classes.

This module will internally store references to all the instances you create with these methods, so that they do not need to be created any more than nessecary. Basically, they are singletons.

create ($package_name, version => ?$version, authority => ?$authority, superclasses => ?@superclasses, methods => ?%methods, attributes => ?%attributes)

This returns a Class::MOP::Class object, bringing the specified $package_name into existence and adding any of the $version, $authority, @superclasses, %methods and %attributes to it.

create_anon_class (superclasses => ?@superclasses, methods => ?%methods, attributes => ?%attributes)

This will create an anonymous class, it works much like create but it does not need a $package_name. Instead it will create a suitably unique package name for you to stash things into.

On very important distinction is that anon classes are destroyed once the metaclass they are attached to goes out of scope. In the DESTROY method, the created package will be removed from the symbol table.

It is also worth noting that any instances created with an anon-class will keep a special reference to the anon-meta which will prevent the anon-class from going out of scope until all instances of it have also been destroyed. This however only works for HASH based instance types, as we use a special reserved slot (__MOP__) to store this.

initialize ($package_name, %options)

This initializes and returns returns a Class::MOP::Class object for a given a $package_name.

reinitialize ($package_name, %options)

This removes the old metaclass, and creates a new one in it's place. Do not use this unless you really know what you are doing, it could very easily make a very large mess of your program.

construct_class_instance (%options)

This will construct an instance of Class::MOP::Class, it is here so that we can actually "tie the knot" for Class::MOP::Class to use construct_instance once all the bootstrapping is done. This method is used internally by initialize and should never be called from outside of that method really.

check_metaclass_compatability

This method is called as the very last thing in the construct_class_instance method. This will check that the metaclass you are creating is compatible with the metaclasses of all your ancestors. For more inforamtion about metaclass compatibility see the About Metaclass compatibility section in Class::MOP.

update_package_cache_flag

This will reset the package cache flag for this particular metaclass it is basically the value of the Class::MOP::get_package_cache_flag function. This is very rarely needed from outside of Class::MOP::Class but in some cases you might want to use it, so it is here.

reset_package_cache_flag

Clears the package cache flag to announce to the internals that we need to rebuild the method map.

Object instance construction and cloning

These methods are entirely optional, it is up to you whether you want to use them or not.

instance_metaclass

Returns the class name of the instance metaclass, see Class::MOP::Instance for more information on the instance metaclasses.

get_meta_instance

Returns an instance of Class::MOP::Instance to be used in the construction of a new instance of the class.

new_object (%params)

This is a convience method for creating a new object of the class, and blessing it into the appropriate package as well. Ideally your class would call a new this method like so:

sub MyClass::new {
    my ($class, %param) = @_;
    $class->meta->new_object(%params);
}
construct_instance (%params)

This method is used to construct an instance structure suitable for bless-ing into your package of choice. It works in conjunction with the Attribute protocol to collect all applicable attributes.

This will construct and instance using a HASH ref as storage (currently only HASH references are supported). This will collect all the applicable attributes and layout out the fields in the HASH ref, it will then initialize them using either use the corresponding key in %params or any default value or initializer found in the attribute meta-object.

clone_object ($instance, %params)

This is a convience method for cloning an object instance, then blessing it into the appropriate package. This method will call clone_instance, which performs a shallow copy of the object, see that methods documentation for more details. Ideally your class would call a clone this method like so:

sub MyClass::clone {
    my ($self, %param) = @_;
    $self->meta->clone_object($self, %params);
}
clone_instance($instance, %params)

This method is a compliment of construct_instance (which means if you override construct_instance, you need to override this one too), and clones the instance shallowly.

The cloned structure returned is (like with construct_instance) an unblessed HASH reference, it is your responsibility to then bless this cloned structure into the right class (which clone_object will do for you).

As of 0.11, this method will clone the $instance structure shallowly, as opposed to the deep cloning implemented in prior versions. After much thought, research and discussion, I have decided that anything but basic shallow cloning is outside the scope of the meta-object protocol. I think Yuval "nothingmuch" Kogman put it best when he said that cloning is too context-specific to be part of the MOP.

rebless_instance($instance, ?%params)

This will change the class of $instance to the class of the invoking Class::MOP::Class. You may only rebless the instance to a subclass of itself. You may pass in optional %params which are like constructor params and will override anything already defined in the instance.

Informational

These are a few predicate methods for asking information about the class.

is_anon_class

This returns true if the class is a Class::MOP::Class created anon class.

is_mutable

This returns true if the class is still mutable.

is_immutable

This returns true if the class has been made immutable.

Inheritance Relationships

superclasses (?@superclasses)

This is a read-write attribute which represents the superclass relationships of the class the Class::MOP::Class instance is associated with. Basically, it can get and set the @ISA for you.

class_precedence_list

This computes the a list of all the class's ancestors in the same order in which method dispatch will be done. This is similair to what Class::ISA::super_path does, but we don't remove duplicate names.

linearized_isa

This returns a list based on class_precedence_list but with all duplicates removed.

subclasses

This returns a list of subclasses for this class.

Methods

get_method_map

Returns a HASH ref of name to CODE reference mapping for this class.

method_metaclass

Returns the class name of the method metaclass, see Class::MOP::Method for more information on the method metaclasses.

add_method ($method_name, $method)

This will take a $method_name and CODE reference to that $method and install it into the class's package.

NOTE: This does absolutely nothing special to $method other than use Sub::Name to make sure it is tagged with the correct name, and therefore show up correctly in stack traces and such.

alias_method ($method_name, $method)

This will take a $method_name and CODE reference to that $method and alias the method into the class's package.

NOTE: Unlike add_method, this will not try to name the $method using Sub::Name, it only aliases the method in the class's package.

has_method ($method_name)

This just provides a simple way to check if the class implements a specific $method_name. It will not however, attempt to check if the class inherits the method (use UNIVERSAL::can for that).

This will correctly handle functions defined outside of the package that use a fully qualified name (sub Package::name { ... }).

This will correctly handle functions renamed with Sub::Name and installed using the symbol tables. However, if you are naming the subroutine outside of the package scope, you must use the fully qualified name, including the package name, for has_method to correctly identify it.

This will attempt to correctly ignore functions imported from other packages using Exporter. It breaks down if the function imported is an __ANON__ sub (such as with use constant), which very well may be a valid method being applied to the class.

In short, this method cannot always be trusted to determine if the $method_name is actually a method. However, it will DWIM about 90% of the time, so it's a small trade off I think.

get_method ($method_name)

This will return a Class::MOP::Method instance related to the specified $method_name, or return undef if that method does not exist.

The Class::MOP::Method is codifiable, so you can use it like a normal CODE reference, see Class::MOP::Method for more information.

find_method_by_name ($method_name)

This will return a CODE reference of the specified $method_name, or return undef if that method does not exist.

Unlike get_method this will also look in the superclasses.

remove_method ($method_name)

This will attempt to remove a given $method_name from the class. It will return the CODE reference that it has removed, and will attempt to use Sub::Name to clear the methods associated name.

get_method_list

This will return a list of method names for all locally defined methods. It does not provide a list of all applicable methods, including any inherited ones. If you want a list of all applicable methods, use the compute_all_applicable_methods method.

compute_all_applicable_methods

This will return a list of all the methods names this class will respond to, taking into account inheritance. The list will be a list of HASH references, each one containing the following information; method name, the name of the class in which the method lives and a CODE reference for the actual method.

find_all_methods_by_name ($method_name)

This will traverse the inheritence hierarchy and locate all methods with a given $method_name. Similar to compute_all_applicable_methods it returns a list of HASH references with the following information; method name (which will always be the same as $method_name), the name of the class in which the method lives and a CODE reference for the actual method.

The list of methods produced is a distinct list, meaning there are no duplicates in it. This is especially useful for things like object initialization and destruction where you only want the method called once, and in the correct order.

find_next_method_by_name ($method_name)

This will return the first method to match a given $method_name in the superclasses, this is basically equivalent to calling SUPER::$method_name, but it can be dispatched at runtime.

Method Modifiers

Method modifiers are a concept borrowed from CLOS, in which a method can be wrapped with before, after and around method modifiers that will be called everytime the method is called.

How method modifiers work?

Method modifiers work by wrapping the original method and then replacing it in the classes symbol table. The wrappers will handle calling all the modifiers in the appropariate orders and preserving the calling context for the original method.

Each method modifier serves a particular purpose, which may not be obvious to users of other method wrapping modules. To start with, the return values of before and after modifiers are ignored. This is because thier purpose is not to filter the input and output of the primary method (this is done with an around modifier). This may seem like an odd restriction to some, but doing this allows for simple code to be added at the begining or end of a method call without jeapordizing the normal functioning of the primary method or placing any extra responsibility on the code of the modifier. Of course if you have more complex needs, then use the around modifier, which uses a variation of continutation passing style to allow for a high degree of flexibility.

Before and around modifiers are called in last-defined-first-called order, while after modifiers are called in first-defined-first-called order. So the call tree might looks something like this:

before 2
 before 1
  around 2
   around 1
    primary
   after 1
  after 2

To see examples of using method modifiers, see the following examples included in the distribution; InstanceCountingClass, Perl6Attribute, AttributesWithHistory and C3MethodDispatchOrder. There is also a classic CLOS usage example in the test 017_add_method_modifier.t.

What is the performance impact?

Of course there is a performance cost associated with method modifiers, but we have made every effort to make that cost be directly proportional to the amount of modifier features you utilize.

The wrapping method does it's best to only do as much work as it absolutely needs to. In order to do this we have moved some of the performance costs to set-up time, where they are easier to amortize.

All this said, my benchmarks have indicated the following:

simple wrapper with no modifiers             100% slower
simple wrapper with simple before modifier   400% slower
simple wrapper with simple after modifier    450% slower
simple wrapper with simple around modifier   500-550% slower
simple wrapper with all 3 modifiers          1100% slower

These numbers may seem daunting, but you must remember, every feature comes with some cost. To put things in perspective, just doing a simple AUTOLOAD which does nothing but extract the name of the method called and return it costs about 400% over a normal method call.

add_before_method_modifier ($method_name, $code)

This will wrap the method at $method_name and the supplied $code will be passed the @_ arguments, and called before the original method is called. As specified above, the return value of the before method modifiers is ignored, and it's ability to modify @_ is fairly limited. If you need to do either of these things, use an around method modifier.

add_after_method_modifier ($method_name, $code)

This will wrap the method at $method_name so that the original method will be called, it's return values stashed, and then the supplied $code will be passed the @_ arguments, and called. As specified above, the return value of the after method modifiers is ignored, and it cannot modify the return values of the original method. If you need to do either of these things, use an around method modifier.

add_around_method_modifier ($method_name, $code)

This will wrap the method at $method_name so that $code will be called and passed the original method as an extra argument at the begining of the @_ argument list. This is a variation of continuation passing style, where the function prepended to @_ can be considered a continuation. It is up to $code if it calls the original method or not, there is no restriction on what the $code can or cannot do.

Attributes

It should be noted that since there is no one consistent way to define the attributes of a class in Perl 5. These methods can only work with the information given, and can not easily discover information on their own. See Class::MOP::Attribute for more details.

attribute_metaclass

Returns the class name of the attribute metaclass, see Class::MOP::Attribute for more information on the attribute metaclasses.

get_attribute_map

This returns a HASH ref of name to attribute meta-object mapping.

add_attribute ($attribute_meta_object | ($attribute_name, %attribute_spec))

This stores the $attribute_meta_object (or creates one from the $attribute_name and %attribute_spec) in the Class::MOP::Class instance associated with the given class. Unlike methods, attributes within the MOP are stored as meta-information only. They will be used later to construct instances from (see construct_instance above). More details about the attribute meta-objects can be found in the Class::MOP::Attribute or the "The Attribute protocol" in Class::MOP section.

It should be noted that any accessor, reader/writer or predicate methods which the $attribute_meta_object has will be installed into the class at this time.

NOTE If an attribute already exists for $attribute_name, the old one will be removed (as well as removing all it's accessors), and then the new one added.

has_attribute ($attribute_name)

Checks to see if this class has an attribute by the name of $attribute_name and returns a boolean.

get_attribute ($attribute_name)

Returns the attribute meta-object associated with $attribute_name, if none is found, it will return undef.

remove_attribute ($attribute_name)

This will remove the attribute meta-object stored at $attribute_name, then return the removed attribute meta-object.

NOTE: Removing an attribute will only affect future instances of the class, it will not make any attempt to remove the attribute from any existing instances of the class.

It should be noted that any accessor, reader/writer or predicate methods which the attribute meta-object stored at $attribute_name has will be removed from the class at this time. This will make these attributes somewhat inaccessable in previously created instances. But if you are crazy enough to do this at runtime, then you are crazy enough to deal with something like this :).

get_attribute_list

This returns a list of attribute names which are defined in the local class. If you want a list of all applicable attributes for a class, use the compute_all_applicable_attributes method.

compute_all_applicable_attributes

This will traverse the inheritance heirachy and return a list of all the applicable attributes for this class. It does not construct a HASH reference like compute_all_applicable_methods because all that same information is discoverable through the attribute meta-object itself.

find_attribute_by_name ($attr_name)

This method will traverse the inheritance heirachy and find the first attribute whose name matches $attr_name, then return it. It will return undef if nothing is found.

Class Immutability

make_immutable (%options)

This method will invoke a tranforamtion upon the class which will make it immutable. Details of this transformation can be found in the Class::MOP::Immutable documentation.

make_mutable

This method will reverse tranforamtion upon the class which made it immutable.

get_immutable_transformer

Return a transformer suitable for making this class immutable or, if this class is immutable, the transformer used to make it immutable.

get_immutable_options

If the class is immutable, return the options used to make it immutable.

create_immutable_transformer

Create a transformer suitable for making this class immutable

AUTHORS

Stevan Little <stevan@iinteractive.com>

COPYRIGHT AND LICENSE

Copyright 2006-2008 by Infinity Interactive, Inc.

http://www.iinteractive.com

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.