1 package Moose::Cookbook::Meta::Recipe5;
3 # ABSTRACT: The "table" attribute as a metaclass trait
12 package MyApp::Meta::Class::Trait::HasTable;
20 package Moose::Meta::Class::Custom::Trait::HasTable;
21 sub register_implementation { 'MyApp::Meta::Class::Trait::HasTable' }
24 use Moose -traits => 'HasTable';
26 __PACKAGE__->meta->table('User');
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>.
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.
40 =head2 Using this Metaclass Trait in Practice
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>:
45 my $table = MyApp::User->meta->table;
48 $table = MyApp::User->meta->table
49 if MyApp::User->meta->meta->can('does')
50 and MyApp::User->meta->meta->does('MyApp::Meta::Class');
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.
56 It's simpler to just write:
58 $table = MyApp::User->meta->table
59 if MyApp::User->meta->can('table');
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.
67 L<Moose::Cookbook::Meta::Recipe3> - Labels implemented via attribute
70 L<Moose::Cookbook::Meta::Recipe4> - Adding a "table" attribute to the