Commit | Line | Data |
daa0fd7d |
1 | package 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 |
30 | This recipe takes the metaclass table attribute from |
19320607 |
31 | L<Moose::Cookbook::Meta::Recipe4> and implements it as a metaclass |
5377c260 |
32 | trait. Traits are just roles, as we saw in |
33 | L<Moose::Cookbook::Meta::Recipe3>. |
c5b9daec |
34 | |
35 | The advantage of using traits is that it's easy to combine multiple |
5377c260 |
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. |
c5b9daec |
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 | |
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 | |
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 | |
c5b9daec |
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 | |
c5b9daec |
73 | =pod |