Commit | Line | Data |
826230c2 |
1 | package Moose::Cookbook::Meta::Table_MetaclassTrait; |
c5b9daec |
2 | |
6d84892d |
3 | # ABSTRACT: Adding a "table" attribute as a metaclass trait |
daa0fd7d |
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 | |
6d84892d |
30 | In this recipe, we'll create a class metaclass trait which has a "table" |
31 | attribute. This trait is for classes associated with a DBMS table, as one |
32 | might do for an ORM. |
c5b9daec |
33 | |
6d84892d |
34 | In this example, the table name is just a string, but in a real ORM |
35 | the table might be an object describing the table. |
c5b9daec |
36 | |
6d84892d |
37 | =head1 THE METACLASS TRAIT |
c5b9daec |
38 | |
6d84892d |
39 | This really is as simple as the recipe L</SYNOPSIS> shows. The trick is |
40 | getting your classes to use this metaclass, and providing some sort of sugar |
41 | for declaring the table. This is covered in |
42 | L<Moose::Cookbook::Extending::Recipe2>, which shows how to make a module like |
43 | C<Moose.pm> itself, with sugar like C<has_table()>. |
c5b9daec |
44 | |
6d84892d |
45 | =head2 Using this Metaclass Trait in Practice |
c5b9daec |
46 | |
5377c260 |
47 | |
6d84892d |
48 | Accessing this new C<table> attribute is quite simple. Given a class |
49 | named C<MyApp::User>, we could simply write the following: |
5377c260 |
50 | |
6d84892d |
51 | my $table = MyApp::User->meta->table; |
52 | |
53 | As long as C<MyApp::User> has arranged to apply the |
54 | C<MyApp::Meta::Class::Trait::HasTable> to its metaclass, this method call just |
55 | works. If we want to be more careful, we can check that the class metaclass |
56 | object has a C<table> method: |
5377c260 |
57 | |
58 | $table = MyApp::User->meta->table |
59 | if MyApp::User->meta->can('table'); |
60 | |
6d84892d |
61 | In theory, this is not entirely correct, since the metaclass might be getting |
62 | its C<table> method from a I<different> trait. In practice, you are unlikely |
63 | to encounter this sort of problem. |
5377c260 |
64 | |
c5b9daec |
65 | =head1 SEE ALSO |
66 | |
b1301316 |
67 | L<Moose::Cookbook::Meta::Labeled_AttributeTrait> - Labels implemented via |
68 | attribute traits |
c5b9daec |
69 | |
c5b9daec |
70 | =pod |