Commit | Line | Data |
c5b9daec |
1 | |
2 | =pod |
3 | |
4 | =head1 NAME |
5 | |
6 | Moose::Cookbook::Meta::Recipe5 - The "table" attribute as a metaclass trait |
7 | |
8 | =head1 SYNOPSIS |
9 | |
10 | package MyApp::Meta::Class::Trait::HasTable; |
11 | use Moose::Role; |
12 | |
6a7e3999 |
13 | has table => ( |
14 | is => 'rw', |
15 | isa => 'Str', |
16 | ); |
c5b9daec |
17 | |
18 | package Moose::Meta::Class::Custom::Trait::HasTable; |
19 | sub register_implementation { 'MyApp::Meta::Class::Trait::HasTable' } |
20 | |
21 | package MyApp::User; |
22 | use Moose -traits => 'HasTable'; |
23 | |
fe015af9 |
24 | __PACKAGE__->meta->table('User'); |
c5b9daec |
25 | |
26 | =head1 DESCRIPTION |
27 | |
5377c260 |
28 | This recipe takes the metaclass table attribute from |
19320607 |
29 | L<Moose::Cookbook::Meta::Recipe4> and implements it as a metaclass |
5377c260 |
30 | trait. Traits are just roles, as we saw in |
31 | L<Moose::Cookbook::Meta::Recipe3>. |
c5b9daec |
32 | |
33 | The advantage of using traits is that it's easy to combine multiple |
5377c260 |
34 | traits, whereas combining multiple metaclass subclasses requires |
35 | creating yet another subclass. With traits, Moose takes care of |
36 | applying them to your metaclass. |
c5b9daec |
37 | |
38 | =head2 Using this Metaclass Trait in Practice |
39 | |
40 | Once this trait has been applied to a metaclass, it looks exactly like |
41 | the example we saw in L<Moose::Cookbook::Meta::Recipe4>: |
42 | |
6a7e3999 |
43 | my $table = MyApp::User->meta->table; |
c5b9daec |
44 | |
5377c260 |
45 | # the safe version |
46 | $table = MyApp::User->meta->table |
47 | if MyApp::User->meta->meta->can('does') |
48 | and MyApp::User->meta->meta->does('MyApp::Meta::Class'); |
49 | |
50 | The safe version is a little complicated. We have to check that the |
51 | metaclass object's metaclass has a C<does> method, in which case we |
52 | can ask if the the metaclass does a given role. |
53 | |
54 | It's simpler to just write: |
55 | |
56 | $table = MyApp::User->meta->table |
57 | if MyApp::User->meta->can('table'); |
58 | |
59 | In theory, this is a little less correct, since the metaclass might be |
60 | getting its C<table> method from a I<different> role. In practice, you |
61 | are unlikely to encounter this sort of problem. |
62 | |
c5b9daec |
63 | =head1 SEE ALSO |
64 | |
65 | L<Moose::Cookbook::Meta::Recipe3> - Labels implemented via attribute |
66 | traits |
67 | |
68 | L<Moose::Cookbook::Meta::Recipe4> - Adding a "table" attribute to the |
69 | metaclass |
70 | |
71 | =head1 AUTHOR |
72 | |
73 | Dave Rolsky E<lt>autarch@urth.orgE<gt> |
74 | |
75 | =head1 COPYRIGHT AND LICENSE |
76 | |
2840a3b2 |
77 | Copyright 2006-2009 by Infinity Interactive, Inc. |
c5b9daec |
78 | |
79 | L<http://www.iinteractive.com> |
80 | |
81 | This library is free software; you can redistribute it and/or modify |
82 | it under the same terms as Perl itself. |
83 | |
84 | =pod |