NAME

Moose::Manual::Delegation - Attribute delegation

WHAT IS DELEGATION?

Delegation is a feature that lets you create "proxy" methods that do nothing more than call some other method on an attribute. This is quite handy since it lets you simplify a complex set of "has-a" relationships and present a single unified API from one class.

With delegation, consumers of a class don't need to know about all the objects it contains, reducing the amount of API they need to learn.

Delegations are defined as a mapping between one or more methods provided by the "real" class (the delegatee), and a set of corresponding methods in the delegating class. The delegating class can re-use the method names provided by the delegatee or provide its own names.

Delegation is also a great way to wrap an existing class, especially a non-Moose class or one that is somehow hard (or impossible) to subclass.

DEFINING A MAPPING

Moose offers a number of options for defining a delegation's mapping, ranging from simple to complex.

The simplest form is to simply specify a list of methods:

  package Website;

  use Moose;

  has 'uri' => (
      is      => 'ro',
      isa     => 'URI',
      handles => [qw( host path )],
  );

With this definition, we can call $website->host and it "just works". Under the hood, Moose will call $website->uri->host for you.

We can also define a mapping as a hash reference. This allows you to rename methods as part of the mapping:

  package Website;

  use Moose;

  has 'uri' => (
      is      => 'ro',
      isa     => 'URI',
      handles => {
          hostname => 'host',
          path     => 'path',
      },
  );

In this example, we've created a $website->hostname method, rather than using URI.pm's name, host.

These two mapping forms are the ones you will use most often. The remainder are a bit more complex, and less common.

  has 'uri' => (
      is      => 'ro',
      isa     => 'URI',
      handles => qr/^(?:host|path|query.*)/,
  );

This is similar to the array version, except it uses the regex to match against all the methods provided by the delegatee. In order for this to work, you must provide an isa parameter for the attribute, and it must be a class. Moose uses this to introspect the delegatee class and determine what methods it provides.

You can use a role name as the value of handles:

  has 'uri' => (
      is      => 'ro',
      isa     => 'URI',
      handles => 'HasURI',
  );

Moose will introspect the role to determine what methods it provides and create a mapping for each of those methods.

Finally, you can also provide a sub reference to generate a mapping. You probably won't need this version often (if ever). See the Moose docs for more details on exactly how this works.

PERL DATA STRUCTURES

Handles also will allow you to delegate to "helper" methods that work on common Perl data structures. If you remember or have ever used MooseX::AttributeHelpers the mechanism is very similar.

  has 'queue' => (
      isa     => 'ArrayRef[Item]',
      traits  => ['Array'],
      default => sub { [ ] },
      handles => {
          add_item  => 'push',
          next_item => 'shift',
      },
  )

By providing the Array trait to the traits parameter you signal to Moose that you would like to use the set of Array helpers. Moose will then create add_item and next_item method that "just works". Behind the scenes add_item is something like

  sub add_item {
      my ($self, @items) = @_;

      for my $item (@items) {
          $Item_TC->validate($item);
      }

      push @{ $self->queue }, @items;
  }

There are traits for not only Array but also Hash, Bool, String, Number, and Counter. For more information see the documentation in Moose::Meta::Attribute::Native.

CURRYING

Currying is a way of creating a method or function from another method or function with some of the parameters pre-defined. Moose provides the ability to curry methods when creating delegates.

    package Spider;
    use Moose;

    has request => (
        is      => 'ro'
        isa     => 'HTTP::Request',
        handles => {
            set_user_agent => [ header => 'UserAgent' ],
        },
    )

With this definition, calling $spider->set_user_agent('MyClient') will behind the scenes call $spider->request->header('UserAgent', 'MyClient').

MISSING ATTRIBUTES

It is perfectly valid to delegate methods to an attribute which is not required or can be undefined. When a delegated method is called, Moose will throw a runtime error if the attribute does not contain an object.

AUTHOR

Dave Rolsky <autarch@urth.org>

COPYRIGHT AND LICENSE

Copyright 2009 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.