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