NAME

Moose::Manual::Attributes - Object attributes with Moose

VERSION

version 2.2009

INTRODUCTION

Moose attributes have many properties, and attributes are probably the single most powerful and flexible part of Moose. You can create a powerful class simply by declaring attributes. In fact, it's possible to have classes that consist solely of attribute declarations.

An attribute is a property that every member of a class has. For example, we might say that "every Person object has a first name and last name". Attributes can be optional, so that we can say "some Person objects have a social security number (and some don't)".

At its simplest, an attribute can be thought of as a named value (as in a hash) that can be read and set. However, attributes can also have defaults, type constraints, delegation and much more.

In other languages, attributes are also referred to as slots or properties.

ATTRIBUTE OPTIONS

Use the has function to declare an attribute:

packagePerson;useMoose;has'first_name'=>(is=>'rw');

This says that all Person objects have an optional read-write "first_name" attribute.

Read-write vs. read-only

The options passed to has define the properties of the attribute. There are many options, but in the simplest form you just need to set is, which can be either ro (read-only) or rw (read-write). When an attribute is rw, you can change it by passing a value to its accessor. When an attribute is ro, you may only read the current value of the attribute through its accessor. You can, however, set the attribute when creating the object by passing it to the constructor.

In fact, you could even omit is, but that gives you an attribute that has no accessor. This can be useful with other attribute options, such as handles. However, if your attribute generates no accessors, Moose will issue a warning, because that usually means the programmer forgot to say the attribute is read-only or read-write. If you really mean to have no accessors, you can silence this warning by setting is to bare.

Accessor methods

Each attribute has one or more accessor methods. An accessor lets you read and write the value of that attribute for an object.

By default, the accessor method has the same name as the attribute. If you declared your attribute as ro then your accessor will be read-only. If you declared it as rw, you get a read-write accessor. Simple.

Given our Person example above, we now have a single first_name accessor that can read or write a Person object's first_name attribute's value.

If you want, you can also explicitly specify the method names to be used for reading and writing an attribute's value. This is particularly handy when you'd like an attribute to be publicly readable, but only privately settable. For example:

has'weight'=>(is=>'ro',writer=>'_set_weight',);

This might be useful if weight is calculated based on other methods. For example, every time the eat method is called, we might adjust weight. This lets us hide the implementation details of weight changes, but still provide the weight value to users of the class.

Some people might prefer to have distinct methods for reading and writing. In Perl Best Practices, Damian Conway recommends that reader methods start with "get_" and writer methods start with "set_".

We can do exactly that by providing names for both the reader and writer methods:

has'weight'=>(is=>'rw',reader=>'get_weight',writer=>'set_weight',);

If you're thinking that doing this over and over would be insanely tedious, you're right! Fortunately, Moose provides a powerful extension system that lets you override the default naming conventions. See Moose::Manual::MooseX for more details.

Predicate and clearer methods

Moose allows you to explicitly distinguish between a false or undefined attribute value and an attribute which has not been set. If you want to access this information, you must define clearer and predicate methods for an attribute.

A predicate method tells you whether or not a given attribute is currently set. Note that an attribute can be explicitly set to undef or some other false value, but the predicate will return true.

The clearer method unsets the attribute. This is not the same as setting the value to undef, but you can only distinguish between them if you define a predicate method!

Here's some code to illustrate the relationship between an accessor, predicate, and clearer method.

When the default is called during object construction, it may be called before other attributes have been set. If your default is dependent on other parts of the object's state, you can make the attribute lazy. Laziness is covered in the next section.

If you want to use a reference of any sort as the default value, you must return it from a subroutine.

has'mapping'=>(is=>'ro',default=>sub{{}},);

This is necessary because otherwise Perl would instantiate the reference exactly once, and it would be shared by all objects:

has'mapping'=>(is=>'ro',default=>{},# wrong!);

Moose will throw an error if you pass a bare non-subroutine reference as the default.

If Moose allowed this then the default mapping attribute could easily end up shared across many objects. Instead, wrap it in a subroutine reference as we saw above.

This is a bit awkward, but it's just the way Perl works.

As an alternative to using a subroutine reference, you can supply a builder method for your attribute:

This has several advantages. First, it moves a chunk of code to its own named method, which improves readability and code organization. Second, because this is a named method, it can be subclassed or provided by a role.

We strongly recommend that you use a builder instead of a default for anything beyond the most trivial default.

A builder, just like a default, is called as a method on the object with no additional parameters.

Builders allow subclassing

Because the builder is called by name, it goes through Perl's method resolution. This means that builder methods are both inheritable and overridable.

Laziness

Moose lets you defer attribute population by making an attribute lazy:

has'size'=>(is=>'ro',lazy=>1,builder=>'_build_size',);

When lazy is true, the default is not generated until the reader method is called, rather than at object construction time. There are several reasons you might choose to do this.

First, if the default value for this attribute depends on some other attributes, then the attribute must be lazy. During object construction, defaults are not generated in a predictable order, so you cannot count on some other attribute being populated when generating a default.

Second, there's often no reason to calculate a default before it's needed. Making an attribute lazy lets you defer the cost until the attribute is needed. If the attribute is never needed, you save some CPU time.

We recommend that you make any attribute with a builder or non-trivial default lazy as a matter of course.

Lazy defaults and $_

Please note that a lazy default or builder can be called anywhere, even inside a map or grep. This means that if your default sub or builder changes $_, something weird could happen. You can prevent this by adding local $_ inside your default or builder.

Constructor parameters (init_arg)

By default, each attribute can be passed by name to the class's constructor. On occasion, you may want to use a different name for the constructor parameter. You may also want to make an attribute unsettable via the constructor.

You can do either of these things with the init_arg option:

has'bigness'=>(is=>'ro',init_arg=>'size',);

Now we have an attribute named "bigness", but we pass size to the constructor.

Even more useful is the ability to disable setting an attribute via the constructor. This is particularly handy for private attributes:

By setting the init_arg to undef, we make it impossible to set this attribute when creating a new object.

Weak references

Moose has built-in support for weak references. If you set the weak_ref option to a true value, then it will call Scalar::Util::weaken whenever the attribute is set:

has'parent'=>(is=>'rw',weak_ref=>1,);$node->parent($parent_node);

This is very useful when you're building objects that may contain circular references.

When the object in a weak reference goes out of scope, the attribute's value will become undef "behind the scenes". This is done by the Perl interpreter directly, so Moose does not see this change. This means that triggers don't fire, coercions aren't applied, etc.

The attribute is not cleared, so a predicate method for that attribute will still return true. Similarly, when the attribute is next accessed, a default value will not be generated.

Triggers

A trigger is a subroutine that is called whenever the attribute is set:

has'size'=>(is=>'rw',trigger=>\&_size_set,);sub _size_set {my($self,$size,$old_size)=@_;my$msg=$self->name;if(@_>2){$msg.=" - old size was $old_size";}$msg.=" - size is now $size";warn$msg;}

The trigger is called after an attribute's value is set. It is called as a method on the object, and receives the new and old values as its arguments. If the attribute had not previously been set at all, then only the new value is passed. This lets you distinguish between the case where the attribute had no value versus when the old value was undef.

This differs from an after method modifier in two ways. First, a trigger is only called when the attribute is set, as opposed to whenever the accessor method is called (for reading or writing). Second, it is also called when an attribute's value is passed to the constructor.

However, triggers are not called when an attribute is populated from a default or builder.

Attribute types

Attributes can be restricted to only accept certain types:

has'first_name'=>(is=>'ro',isa=>'Str',);

This says that the first_name attribute must be a string.

Moose also provides a shortcut for specifying that an attribute only accepts objects that do a certain role:

The advantage of traits is that you can mix more than one of them together easily (in fact, a trait is just a role under the hood).

There are a number of MooseX modules on CPAN which provide useful attribute metaclasses and traits. See Moose::Manual::MooseX for some examples. You can also write your own metaclasses and traits. See the "Meta" and "Extending" recipes in Moose::Cookbook for examples.

Native Delegations

Native delegations allow you to delegate to standard Perl data structures as if they were objects.

For example, we can pretend that an array reference has methods like push(), shift(), map(), count(), and more.

ATTRIBUTE INHERITANCE

By default, a child inherits all of its parent class(es)' attributes as-is. However, you can change most aspects of the inherited attribute in the child class. You cannot change any of its associated method names (reader, writer, predicate, etc).

To change some aspects of an attribute, you simply prepend a plus sign (+) to its name:

Now the first_name attribute in LazyPerson is lazy, and defaults to 'Bill'.

We recommend that you exercise caution when changing the type (isa) of an inherited attribute.

Attribute Inheritance and Method Modifiers

When an inherited attribute is defined, that creates an entirely new set of accessors for the attribute (reader, writer, predicate, etc.). This is necessary because these may be what was changed when inheriting the attribute.

As a consequence, any method modifiers defined on the attribute's accessors in an ancestor class will effectively be ignored, because the new accessors live in the child class and do not see the modifiers from the parent class.

MULTIPLE ATTRIBUTE SHORTCUTS

If you have a number of attributes that differ only by name, you can declare them all at once:

MORE ON ATTRIBUTES

Moose attributes are a big topic, and this document glosses over a few aspects. We recommend that you read the Moose::Manual::Delegation and Moose::Manual::Types documents to get a more complete understanding of attribute features.

A FEW MORE OPTIONS

Moose has lots of attribute options. The ones listed below are superseded by some more modern features, but are covered for the sake of completeness.

The documentation option

You can provide a piece of documentation as a string for an attribute: