Moose

Delegations

Alternatively, you could utilize Moose's delegation feature when you set up the fired_dt attribute, like this:


has 'fired_dt' => ( 
        is => 'rw', 
        isa => 'DateTime',
        handles => {
                last_fired => 'datetime'
        }
);

This will set up another accessor method named last_fired and map it to the datetime method of the attribute. This makes the invocations of $self->last_fired and $self->fired_dt->datetime equivalent. This is worthwhile because it allows you to keep your API simpler.

Types

Moose provides its own type system for enforcing constraints on the value to which an attribute can be set. As I mentioned earlier, type constraints are set with the isa attribute option.

Moose provides a built-in hierarchy of named types for general-purpose use. For example, Int is a subtype of Num, and Num is a subtype of Str. The value 'foo' would pass Str but not Num or Int; 3.4 would pass Str and Num but not Int, and 7 would pass all of Str, Num and Int.

There also are certain built-in types that can be "parameterized", such as ArrayRef (a reference to an array). This lets you not only require an attribute to contain an ArrayRef, but also set type constraints on the values that ArrayRef can contain. For example, setting isa => 'ArrayRef[Int]' requires an ArrayRef of Ints. These can be nested multiple levels deep, such as 'ArrayRef[HashRef[Str]]' and so on.

Another special parameterized type is Maybe, which allows a value to be undef. For example, 'Maybe[Num]' means the value is either undef or a Num.

You also can use type "unions". For example, 'Bool | Ref' means either Bool or Ref.

If the built-in types aren't sufficient for your needs, you can define your own subtypes to do any kind of custom validation you want. The Moose::Util::TypeConstraints documentation provides details on creating subtypes, as well as a complete listing of the built-in types that are available (see Resources).

Finally, instead of specifying the name of a defined type, you can specify a class name, which will require an object of that class type (such as in our DateTime attribute example). All of these concepts can be intermixed for maximum flexibility. So, for example, if you set isa => 'ArrayRef[MyApp::Rifle]', it would require an ArrayRef of MyApp::Rifle objects.

Inheritance

Subclassing is relatively painless in Moose. Use the extends function to make a class a subclass of another. The subclass inherits all the parent's methods and attributes, and then you can define new ones or override existing ones simply by defining them again.

Moose also provides helpful attribute inheritance sugar that allows you to inherit an attribute from the parent, but override specific options in the subclass. To tell Moose to do this, prepend the attribute name with a plus sign (+) in a "has" declaration in the subclass. (Note: attribute options related to accessor method names cannot be changed using this technique.)

For example, you could create a new class named MyApp::AutomaticRifle that inherits from the MyApp::Rifle class from the previous example:


<![CDATA[
package MyApp::AutomaticRifle;
use Moose;
extends 'MyApp::Rifle';

has '+rounds' => ( default => 50 );
has 'last_burst_num' => ( is => 'rw', isa => 'Int' );

sub burst_fire {
        my ($self, $num) = @_;
	
        $self->last_burst_num($num);

        for (my $i=0; $i<$num; $i++) {
                $self->fire;
        }
}

1;
]]>

Here, MyApp::AutomaticRifle can do everything MyApp::Rifle can do, but it also can "burst_fire". Also, the default of the rounds attribute has been changed to 50 in AutomaticRifle, but the rest of the options for the rounds attribute still are inherited from the parent Rifle class.

You might use MyApp::AutomaticRifle like this:


use strict;
use MyApp::AutomaticRifle;

my $rifle = MyApp::AutomaticRifle->new;
print "There are " . $rifle->rounds . " rounds in the rifle\n";
$rifle->burst_fire(35);
print "Now there are " . $rifle->rounds . " rounds in the rifle\n";

The BUILD Method

Although Moose automatically sets up the "new" constructor for you, there still are times when you need to execute custom code at construction. If you need to do that, define a method named BUILD, and it will be called immediately after the object has been constructed. Don't create a "new" method; that will interfere with Moose's operation.

BUILD is also special as it relates to inheritance. Unlike normal methods that override the parents' methods when redefined in subclasses, BUILD can be defined in every class in the inheritance tree and every one will be called, in order from parent to child.

Roles

Roles define some set of behaviors (attributes and methods) without being full-blown classes themselves (capable of instantiation as objects directly). Instead, Roles are "composed" into other classes, applying the defined behaviors to those classes. Roles are conceptually similar to "mixins" in Ruby.

Roles also can require that consuming classes have certain methods by calling the "requires" sugar function in the Role definition (or throw an exception).

You call the "with" sugar function to consume a Role by name, just like you call "extends" to inherit from a regular class.

Here is an example of a simple Role that could be composed into either MyApp::Rifle or MyApp::AutomaticRifle:


package MyApp::FireAll;
use strict;
use Moose::Role;

requires 'fire', 'rounds';

sub fire_all {
        my $self = shift;
        $self->fire while($self->rounds > 0);
}

1;

You would then add this single line to MyApp::Rifle or MyApp::AutomaticRifle to give either class the fire_all method:


with 'MyApp::FireAll';

In the case of MyApp::AutomaticRifle, the with statement must be called after the extends statement, because the "fire" and "rounds" methods don't exist within MyApp::AutomaticRifle before that, and the Role's requires statements would fail.

If you add the Role to MyApp::Rifle, it will be inherited by MyApp::AutomaticRifle automatically, so there would be no need to add it there also (although it won't break anything if you do).

______________________

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

I guess the basic question

ionutpop's picture

I guess the basic question this raises is whether ease of development for you beats usefulness to others. If that ticket is representative, it suggests that actual users feel that converting to Moose is transferring an unwelcome cost them, and so you might end up with modules that are easy to maintain, but unused. That more people might use Moose in the future is speculation, but this complaint is from an actual user.

Perhaps it would be better to wait for requests to Moose-ify existing modules, and if they don’t come, don’t bother. If converting to Moose is that simple, surely someone will send some patches to you, or fork the module, if they want a Moose version.

Instead, just consider Moose for new code, where there is no opportunity to encourage take-up by people looking for lightweight code, only to find it switched to what they think is heaviness after the fact.

Ianis from bet365.com

nice of artical Save the

juliajin's picture

nice of artical Save the aloft chic analogue into a book called MyApp/Rifle.pm aural one of your Perl's cover directories, and again you can use it in a Perl affairs like this. jogos de motos

Moose is awesome!

Chankey Pathak's picture

Thanks for this tutorial on Moose. Moose is simply awesome!

Intresting I have ner use

pilot school's picture

Intresting I have ner use Mose, but after reading this i might give it a try

----- http://ai.vc/zd

bdso8f9sa's picture

----- http://ai.vc/zd -----

Hi,Dear Ladies and Gentlemen,
1. sport shoes : Jordan ,Nike, adidas, Puma, Gucci, LV, UGG , etc. including women shoes and kids shoes.
2. T-Shirts : BBC T-Shirts, Bape T-Shirts, Armani T-Shirts, Polo T-Shirts,etc.
3. Hoodies : Bape hoody, hoody, AFF hoody, GGG hoody, ED hoody ,etc.
4. Jeans : Levis jeans , Gucci jeans, jeans, Bape jeans , DG jeans ,etc.
----- http://ai.vc/zd -----
----- http://ai.vc/zd -----

Service is our Lift.

enjoy yourself.

thank you!!

::∴★∵**☆.∴★∵**☆.∴★∵**☆.
█████.::∴★∵**☆.∴★∵**☆.
█田█田█::∴★∵**☆.∴★∵**☆.
█田█田█.∴★∵**☆.∴★∵**☆.
█田█田█∴★∵**☆.∴★∵**☆.
█田█田█.★∵**☆.∴★∵**☆.
█████.*******************
◢██□██◣.~~~~~*^_^*

thanx

Benzeb's picture

thanx for this article.
I've been laying with perl for some years now, but never gave a try to Moose.
Now that i have a clearer view to what Moose it, i have to try it

ps : Perl IS wonderful !! Can't understand why people enjoy php much more than Perl

Webinar
One Click, Universal Protection: Implementing Centralized Security Policies on Linux Systems

As Linux continues to play an ever increasing role in corporate data centers and institutions, ensuring the integrity and protection of these systems must be a priority. With 60% of the world's websites and an increasing share of organization's mission-critical workloads running on Linux, failing to stop malware and other advanced threats on Linux can increasingly impact an organization's reputation and bottom line.

Learn More

Sponsored by Bit9

Webinar
Linux Backup and Recovery Webinar

Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.

In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.

Learn More

Sponsored by Storix