stop recommending the register_implementation thing
[gitmo/Moose.git] / lib / Moose / Cookbook / Meta / Table_MetaclassTrait.pod
1 package Moose::Cookbook::Meta::Table_MetaclassTrait;
2
3 # ABSTRACT: Adding a "table" attribute as a metaclass trait
4
5 __END__
6
7
8 =pod
9
10 =begin testing-SETUP
11
12 BEGIN {
13   package MyApp::Meta::Class::Trait::HasTable;
14   use Moose::Role;
15
16   has table => (
17       is  => 'rw',
18       isa => 'Str',
19   );
20 }
21
22 =end testing-SETUP
23
24 =head1 SYNOPSIS
25
26   # in lib/MyApp/Meta/Class/Trait/HasTable.pm
27   package MyApp::Meta::Class::Trait::HasTable;
28   use Moose::Role;
29   Moose::Util::meta_class_alias('HasTable');
30
31   has table => (
32       is  => 'rw',
33       isa => 'Str',
34   );
35
36   # in lib/MyApp/User.pm
37   package MyApp::User;
38   use Moose -traits => 'HasTable';
39
40   __PACKAGE__->meta->table('User');
41
42 =head1 DESCRIPTION
43
44 In this recipe, we'll create a class metaclass trait which has a "table"
45 attribute. This trait is for classes associated with a DBMS table, as one
46 might do for an ORM.
47
48 In this example, the table name is just a string, but in a real ORM
49 the table might be an object describing the table.
50
51 =head1 THE METACLASS TRAIT
52
53 This really is as simple as the recipe L</SYNOPSIS> shows. The trick is
54 getting your classes to use this metaclass, and providing some sort of sugar
55 for declaring the table. This is covered in
56 L<Moose::Cookbook::Extending::Debugging_BaseClassRole>, which shows how to
57 make a module like C<Moose.pm> itself, with sugar like C<has_table()>.
58
59 =head2 Using this Metaclass Trait in Practice
60
61 Accessing this new C<table> attribute is quite simple. Given a class
62 named C<MyApp::User>, we could simply write the following:
63
64   my $table = MyApp::User->meta->table;
65
66 As long as C<MyApp::User> has arranged to apply the
67 C<MyApp::Meta::Class::Trait::HasTable> to its metaclass, this method call just
68 works. If we want to be more careful, we can check that the class metaclass
69 object has a C<table> method:
70
71   $table = MyApp::User->meta->table
72       if MyApp::User->meta->can('table');
73
74 In theory, this is not entirely correct, since the metaclass might be getting
75 its C<table> method from a I<different> trait. In practice, you are unlikely
76 to encounter this sort of problem.
77
78 =head1 RECIPE CAVEAT
79
80 This recipe doesn't work when you paste it all into a single file. This is
81 because the C<< use Moose -traits => 'HasTable'; >> line ends up being
82 executed before the C<table> attribute is defined.
83
84 When the two packages are separate files, this just works.
85
86 =head1 SEE ALSO
87
88 L<Moose::Cookbook::Meta::Labeled_AttributeTrait> - Labels implemented via
89 attribute traits
90
91 =pod
92
93 =begin testing
94
95 can_ok( MyApp::User->meta, 'table' );
96 is( MyApp::User->meta->table, 'User', 'My::User table is User' );
97
98 =end testing