Hi! Please consider following me on twitter: @hanekomu.

Dissecting the Moose Part 1

Jesse Vincent (obra) said on IRC: "Moose looks big and scary, but turns out to be a big kitten. It still has claws, but it mostly is content to sit around in the sun and let you stroke its chin. In return, it looks pretty and entertains you."

But now I want to look inside Moose. Moose is basically a set of layers above Class::MOP. There is the syntactic sugar for the end-user, and a set of custom meta-classes underneath. Moose never creates objects or methods directly; it uses the underlying meta-object protocol to do that. For now, just have a brief look at interacting with Class::MOP:

#!/usr/bin/env perl

use warnings;
use strict;
use Data::Semantic::Net::IPAddress::IPv4;
use Class::MOP;
use Data::Dumper;

my $o = Data::Semantic::Net::IPAddress::IPv4->new;
my $meta = Class::MOP::Class->initialize(ref $o);
my @parents = $meta->class_precedence_list;
warn Data::Dumper->Dump([\@parents, $meta], [qw/*parents meta/]);

So here we create some standard object normally, but then we put the class under the care of Class::MOP. Now we can introspect the class with MOP methods like class_precedence_list(), which gives us a list of all parent classes. We also dump the meta-object itself to see what's going on.

@parents = (
             'Data::Semantic::Net::IPAddress::IPv4',
             'Data::Semantic::Net::IPAddress',
             'Data::Semantic::Net',
             'Data::Semantic',
             'Class::Accessor::Complex',
             'Class::Accessor',
             'Class::Accessor::Installer'
           );
$meta = bless( {
                 'namespace' => \undef,
                 'version' => $meta->{'namespace'},
                 'superclasses' => $meta->{'namespace'},
                 'method_metaclass' => 'Class::MOP::Method',
                 'attribute_metaclass' => 'Class::MOP::Attribute',
                 'package' => 'Data::Semantic::Net::IPAddress::IPv4',
                 'instance_metaclass' => 'Class::MOP::Instance',
                 'methods' => {},
                 'authority' => $meta->{'namespace'},
                 'attributes' => {}
               }, 'Class::MOP::Class' );

Here we can see that if we ask Class::MOP to create an instance of the class it will use Class::MOP::Instance to do it; if we want to add or inspect an attribute, it will use Class::MOP::Attribute to do it. If we wanted to change the way Class::MOP interacts with our previously standard Perl class, we could tell the meta-object to use different meta-classes.

This was not intended to be a complete tutorial of any sort; I'm just writing down things I'm discovering along the way.

Tags: .

Write a comment | Bookmark and Share

posted at: 10:03 | path: /dev | permalink | 0 comments | 0 trackbacks

Comments are closed for this story.

Trackbacks are closed for this story.