Class::MOP::Class(3p)

NAME
Class::MOP::Class - Class Meta Object

VERSION
version 2.2201

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
The Class Protocol is the largest and most complex part of the Class::MOP meta-object protocol. It controls the introspection and manipulation of Perl 5 classes, and it can create them as well. The best way to understand what this module can do is to read the documentation for each of its methods.

INHERITANCE
"Class::MOP::Class" is a subclass of Class::MOP::Module.

METHODS

  Class construction
These methods all create new "Class::MOP::Class" objects. These objects can represent existing classes or they can be used to create new classes from scratch.

The metaclass object for a given class is a singleton. If you attempt to create a metaclass for the same class twice, you will just get the existing object.

Class::MOP::Class->create($package_name, %options)
    This method creates a new "Class::MOP::Class" object with the given package name. It accepts a number of options:

    •   version

        An optional version number for the newly created package.

    •   authority

        An optional authority for the newly created package. See "authority" in Class::MOP::Module for more details.

    •   superclasses

        An optional array reference of superclass names.

    •   methods

        An optional hash reference of methods for the class. The keys of the hash reference are method names and values are subroutine references.

    •   attributes

        An optional array reference of Class::MOP::Attribute objects.

    •   meta_name

        Specifies the name to install the "meta" method for this class under. If it is not passed, "meta" is assumed, and if "undef" is explicitly given, no meta method will be installed.

    •   weaken

        If true, the metaclass that is stored in the global cache will be a weak reference.

        Classes created in this way are destroyed once the metaclass they are attached to goes out of scope, and will be removed from Perl's internal symbol table.

        All instances of a class with a weakened metaclass keep a special reference to the metaclass object, which prevents the metaclass from going out of scope while any instances exist.

        This only works if the instance is based on a hash reference, however.

Class::MOP::Class->create_anon_class(%options)
    This method works just like "Class::MOP::Class->create" but it creates an "anonymous" class. In fact, the class does have a name, but that name is a unique name generated internally by this module.

    It accepts the same "superclasses", "methods", and "attributes" parameters that "create" accepts.

    It also accepts a "cache" option. If this is "true", then the anonymous class will be cached based on its superclasses and roles. If an existing anonymous class in the cache has the same superclasses and roles, it will be reused.

    Anonymous classes default to "weaken => 1" if cache is "false", although this can be overridden.

Class::MOP::Class->initialize($package_name, %options)
    This method will initialize a "Class::MOP::Class" object for the named package. Unlike "create", this method will not create a new class.

    The purpose of this method is to retrieve a "Class::MOP::Class" object for introspecting an existing class.

    If an existing "Class::MOP::Class" object exists for the named package, it will be returned, and any options provided will be ignored!

    If the object does not yet exist, it will be created.

    The valid options that can be passed to this method are "attribute_metaclass", "method_metaclass", "wrapped_method_metaclass", and "instance_metaclass". These are all optional, and default to the appropriate class in the "Class::MOP" distribution.

  Object instance construction and cloning
These methods are all related to creating and/or cloning object instances.

$metaclass->clone_object($instance, %params)
    This method clones an existing object instance. Any parameters you provide are will override existing attribute values in the object.

    This is a convenience method for cloning an object instance, then blessing it into the appropriate package.

    You could implement a clone method in your class, using this method:

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

$metaclass->rebless_instance($instance, %params)
    This method changes the class of $instance to the metaclass's class.

    You can only rebless an instance into a subclass of its current class. If you pass any additional parameters, these will be treated like constructor parameters and used to initialize the object's attributes. Any existing attributes that are already set will be overwritten.

    Before reblessing the instance, this method will call "rebless_instance_away" on the instance's current metaclass. This method will be passed the instance, the new metaclass, and any parameters specified to "rebless_instance". By default, "rebless_instance_away" does nothing; it is merely a hook.

$metaclass->rebless_instance_back($instance)
    Does the same thing as "rebless_instance", except that you can only rebless an instance into one of its superclasses. Any attributes that do not exist in the superclass will be deinitialized.

    This is a much more dangerous operation than "rebless_instance", especially when multiple inheritance is involved, so use this carefully!

$metaclass->new_object(%params)
    This method is used to create a new object of the metaclass's class. Any parameters you provide are used to initialize the instance's attributes. A special "__INSTANCE__" key can be passed to provide an already generated instance, rather than having Class::MOP generate it for you. This is mostly useful for using Class::MOP with foreign classes which generate instances using their own constructors.

$metaclass->instance_metaclass
    Returns the class name of the instance metaclass. See Class::MOP::Instance for more information on the instance metaclass.

$metaclass->get_meta_instance
    Returns an instance of the "instance_metaclass" to be used in the construction of a new instance of the class.

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

$metaclass->is_anon_class
    This returns true if the class was created by calling "Class::MOP::Class->create_anon_class".

$metaclass->is_mutable
    This returns true if the class is still mutable.

$metaclass->is_immutable
    This returns true if the class has been made immutable.

$metaclass->is_pristine
    A class is not pristine if it has non-inherited attributes or if it has any generated methods.

  Inheritance Relationships

$metaclass->superclasses(@superclasses)
    This is a read-write accessor which represents the superclass relationships of the metaclass's class.

    This is basically sugar around getting and setting @ISA.

$metaclass->class_precedence_list
    This returns a list of all of the class's ancestor classes. The classes are returned in method dispatch order.

$metaclass->linearized_isa
    This returns a list based on "class_precedence_list" but with all duplicates removed.

$metaclass->subclasses
    This returns a list of all subclasses for this class, even indirect subclasses.

$metaclass->direct_subclasses
    This returns a list of immediate subclasses for this class, which does not include indirect subclasses.

  Method introspection and creation
These methods allow you to introspect a class's methods, as well as add, remove, or change methods.

Determining what is truly a method in a Perl 5 class requires some heuristics (aka guessing).

Methods defined outside the package with a fully qualified name ("sub Package::name { ... }") will be included. Similarly, methods named with a fully qualified name using Sub::Util are also included.

However, we attempt to ignore imported functions.

Ultimately, we are using heuristics to determine what truly is a method in a class, and these heuristics may get the wrong answer in some edge cases. However, for most "normal" cases the heuristics work correctly.

$metaclass->get_method($method_name)
    This will return a Class::MOP::Method for the specified $method_name. If the class does not have the specified method, it returns "undef"

$metaclass->has_method($method_name)
    Returns a boolean indicating whether or not the class defines the named method. It does not include methods inherited from parent classes.

$metaclass->get_method_list
    This will return a list of method names for all methods defined in this class.

$metaclass->add_method($method_name, $method)
    This method takes a method name and a subroutine reference, and adds the method to the class.

    The subroutine reference can be a Class::MOP::Method, and you are strongly encouraged to pass a meta method object instead of a code reference. If you do so, that object gets stored as part of the class's method map directly. If not, the meta information will have to be recreated later, and may be incorrect.

    If you provide a method object, this method will clone that object if the object's package name does not match the class name. This lets us track the original source of any methods added from other classes (notably Moose roles).

$metaclass->remove_method($method_name)
    Remove the named method from the class. This method returns the Class::MOP::Method object for the method.

$metaclass->method_metaclass
    Returns the class name of the method metaclass, see Class::MOP::Method for more information on the method metaclass.

$metaclass->wrapped_method_metaclass
    Returns the class name of the wrapped method metaclass, see Class::MOP::Method::Wrapped for more information on the wrapped method metaclass.

$metaclass->get_all_methods
    This will traverse the inheritance hierarchy and return a list of all the Class::MOP::Method objects for this class and its parents.

$metaclass->find_method_by_name($method_name)
    This will return a Class::MOP::Method for the specified $method_name. If the class does not have the specified method, it returns "undef"

    Unlike "get_method", this method will look for the named method in superclasses.

$metaclass->get_all_method_names
    This will return a list of method names for all of this class's methods, including inherited methods.

$metaclass->find_all_methods_by_name($method_name)
    This method looks for the named method in the class and all of its parents. It returns every matching method it finds in the inheritance tree, so it returns a list of methods.

    Each method is returned as a hash reference with three keys. The keys are "name", "class", and "code". The "code" key has a Class::MOP::Method object as its value.

    The list of methods is distinct.

$metaclass->find_next_method_by_name($method_name)
    This method returns the first method in any superclass matching the given name. It is effectively the method that "SUPER::$method_name" would dispatch to.

  Attribute introspection and creation
Because Perl 5 does not have a core concept of attributes in classes, we can only return information about attributes which have been added via this class's methods. We cannot discover information about attributes which are defined in terms of "regular" Perl 5 methods.

$metaclass->get_attribute($attribute_name)
    This will return a Class::MOP::Attribute for the specified $attribute_name. If the class does not have the specified attribute, it returns "undef".

    NOTE that get_attribute does not search superclasses, for that you need to use "find_attribute_by_name".

$metaclass->has_attribute($attribute_name)
    Returns a boolean indicating whether or not the class defines the named attribute. It does not include attributes inherited from parent classes.

$metaclass->get_attribute_list
    This will return a list of attributes names for all attributes defined in this class. Note that this operates on the current class only, it does not traverse the inheritance hierarchy.

$metaclass->get_all_attributes
    This will traverse the inheritance hierarchy and return a list of all the Class::MOP::Attribute objects for this class and its parents.

$metaclass->find_attribute_by_name($attribute_name)
    This will return a Class::MOP::Attribute for the specified $attribute_name. If the class does not have the specified attribute, it returns "undef".

    Unlike "get_attribute", this attribute will look for the named attribute in superclasses.

$metaclass->add_attribute(...)
    This method accepts either an existing Class::MOP::Attribute object or parameters suitable for passing to that class's "new" method.

    The attribute provided will be added to the class.

    Any accessor methods defined by the attribute will be added to the class when the attribute is added.

    If an attribute of the same name already exists, the old attribute will be removed first.

$metaclass->remove_attribute($attribute_name)
    This will remove the named attribute from the class, and Class::MOP::Attribute object.

    Removing an attribute also removes any accessor methods defined by the attribute.

    However, note that removing an attribute will only affect future object instances created for this class, not existing instances.

$metaclass->attribute_metaclass
    Returns the class name of the attribute metaclass for this class. By default, this is Class::MOP::Attribute.

  Overload introspection and creation
These methods provide an API to the core overload functionality.

$metaclass->is_overloaded
    Returns true if overloading is enabled for this class. Corresponds to "is_overloaded" in Devel::OverloadInfo.

$metaclass->get_overloaded_operator($op)
    Returns the Class::MOP::Overload object corresponding to the operator named $op, if one exists for this class.

$metaclass->has_overloaded_operator($op)
    Returns whether or not the operator $op is overloaded for this class.

$metaclass->get_overload_list
    Returns a list of operator names which have been overloaded (see "Overloadable Operations" in overload for the list of valid operator names).

$metaclass->get_all_overloaded_operators
    Returns a list of Class::MOP::Overload objects corresponding to the operators that have been overloaded.

$metaclass->add_overloaded_operator($op, $impl)
    Overloads the operator $op for this class. The $impl can be a coderef, a method name, or a Class::MOP::Overload object. Corresponds to "use overload $op => $impl;"

$metaclass->remove_overloaded_operator($op)
    Remove overloading for operator $op. Corresponds to "no overload $op;"

$metaclass->get_overload_fallback_value
    Returns the overload "fallback" setting for the package.

$metaclass->set_overload_fallback_value($fallback)
    Sets the overload "fallback" setting for the package.

  Class Immutability
Making a class immutable "freezes" the class definition. You can no longer call methods which alter the class, such as adding or removing methods or attributes.

Making a class immutable lets us optimize the class by inlining some methods, and also allows us to optimize some methods on the metaclass object itself.

After immutabilization, the metaclass object will cache most informational methods that returns information about methods or attributes. Methods which would alter the class, such as "add_attribute" and "add_method", will throw an error on an immutable metaclass object.

The immutabilization system in Moose takes much greater advantage of the inlining features than Class::MOP itself does.

$metaclass->make_immutable(%options)
    This method will create an immutable transformer and use it to make the class and its metaclass object immutable, and returns true (you should not rely on the details of this value apart from its truth).

    This method accepts the following options:

    •   inline_accessors

    •   inline_constructor

    •   inline_destructor

        These are all booleans indicating whether the specified method(s) should be inlined.

        By default, accessors and the constructor are inlined, but not the destructor.

    •   immutable_trait

        The name of a class which will be used as a parent class for the metaclass object being made immutable. This "trait" implements the post-immutability functionality of the metaclass (but not the transformation itself).

        This defaults to Class::MOP::Class::Immutable::Trait.

    •   constructor_name

        This is the constructor method name. This defaults to "new".

    •   constructor_class

        The name of the method metaclass for constructors. It will be used to generate the inlined constructor. This defaults to "Class::MOP::Method::Constructor".

    •   replace_constructor

        This is a boolean indicating whether an existing constructor should be replaced when inlining a constructor. This defaults to false.

    •   destructor_class

        The name of the method metaclass for destructors. It will be used to generate the inlined destructor. This defaults to "Class::MOP::Method::Denstructor".

    •   replace_destructor

        This is a boolean indicating whether an existing destructor should be replaced when inlining a destructor. This defaults to false.

$metaclass->immutable_options
    Returns a hash of the options used when making the class immutable, including both defaults and anything supplied by the user in the call to "$metaclass->make_immutable". This is useful if you need to temporarily make a class mutable and then restore immutability as it was before.

$metaclass->make_mutable
    Calling this method reverse the immutabilization transformation.

  Method Modifiers
Method modifiers are hooks which allow a method to be wrapped with before, after and around method modifiers. Every time a method is called, its modifiers are also called.

A class can modify its own methods, as well as methods defined in parent classes.

How method modifiers work?

Method modifiers work by wrapping the original method and then replacing it in the class's symbol table. The wrappers will handle calling all the modifiers in the appropriate order and preserving the calling context for the original method.

The return values of "before" and "after" modifiers are ignored. This is because their 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 beginning or end of a method call without altering the function of the wrapped method or placing any extra responsibility on the code of the modifier.

Of course if you have more complex needs, you can use the "around" modifier which allows you to change both the parameters passed to the wrapped method, as well as its return value.

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
     around 1
    around 2
   after 1
  after 2

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 directly proportional to the number of modifier features you use.

The wrapping method does its 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, our 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.

$metaclass->add_before_method_modifier($method_name, $code)
    This wraps the specified method with the supplied subroutine reference. The modifier will be called as a method itself, and will receive the same arguments as are passed to the method.

    When the modifier exits, the wrapped method will be called.

    The return value of the modifier will be ignored.

$metaclass->add_after_method_modifier($method_name, $code)
    This wraps the specified method with the supplied subroutine reference. The modifier will be called as a method itself, and will receive the same arguments as are passed to the method.

    When the wrapped methods exits, the modifier will be called.

    The return value of the modifier will be ignored.

$metaclass->add_around_method_modifier($method_name, $code)
    This wraps the specified method with the supplied subroutine reference.

    The first argument passed to the modifier will be a subroutine reference to the wrapped method. The second argument is the object, and after that come any arguments passed when the method is called.

    The around modifier can choose to call the original method, as well as what arguments to pass if it does so.

    The return value of the modifier is what will be seen by the caller.

  Introspection

Class::MOP::Class->meta
    This will return a Class::MOP::Class instance for this class.

    It should also be noted that Class::MOP will actually bootstrap this module by installing a number of attribute meta-objects into its metaclass.

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>

COPYRIGHT AND LICENSE
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.