Removed Meta recipe2 (an attribute metaclass)
[gitmo/Moose.git] / lib / Moose / Cookbook / Meta / Recipe5.pod
CommitLineData
daa0fd7d 1package Moose::Cookbook::Meta::Recipe5;
c5b9daec 2
daa0fd7d 3# ABSTRACT: The "table" attribute as a metaclass trait
4
5__END__
c5b9daec 6
c5b9daec 7
daa0fd7d 8=pod
c5b9daec 9
10=head1 SYNOPSIS
11
12 package MyApp::Meta::Class::Trait::HasTable;
13 use Moose::Role;
14
6a7e3999 15 has table => (
16 is => 'rw',
17 isa => 'Str',
18 );
c5b9daec 19
20 package Moose::Meta::Class::Custom::Trait::HasTable;
21 sub register_implementation { 'MyApp::Meta::Class::Trait::HasTable' }
22
23 package MyApp::User;
24 use Moose -traits => 'HasTable';
25
fe015af9 26 __PACKAGE__->meta->table('User');
c5b9daec 27
28=head1 DESCRIPTION
29
5377c260 30This recipe takes the metaclass table attribute from
19320607 31L<Moose::Cookbook::Meta::Recipe4> and implements it as a metaclass
5377c260 32trait. Traits are just roles, as we saw in
33L<Moose::Cookbook::Meta::Recipe3>.
c5b9daec 34
35The advantage of using traits is that it's easy to combine multiple
5377c260 36traits, whereas combining multiple metaclass subclasses requires
37creating yet another subclass. With traits, Moose takes care of
38applying them to your metaclass.
c5b9daec 39
40=head2 Using this Metaclass Trait in Practice
41
42Once this trait has been applied to a metaclass, it looks exactly like
43the example we saw in L<Moose::Cookbook::Meta::Recipe4>:
44
6a7e3999 45 my $table = MyApp::User->meta->table;
c5b9daec 46
5377c260 47 # the safe version
48 $table = MyApp::User->meta->table
49 if MyApp::User->meta->meta->can('does')
50 and MyApp::User->meta->meta->does('MyApp::Meta::Class');
51
52The safe version is a little complicated. We have to check that the
53metaclass object's metaclass has a C<does> method, in which case we
54can ask if the the metaclass does a given role.
55
56It's simpler to just write:
57
58 $table = MyApp::User->meta->table
59 if MyApp::User->meta->can('table');
60
61In theory, this is a little less correct, since the metaclass might be
62getting its C<table> method from a I<different> role. In practice, you
63are unlikely to encounter this sort of problem.
64
c5b9daec 65=head1 SEE ALSO
66
67L<Moose::Cookbook::Meta::Recipe3> - Labels implemented via attribute
68traits
69
70L<Moose::Cookbook::Meta::Recipe4> - Adding a "table" attribute to the
71metaclass
72
c5b9daec 73=pod