Remove meta recipe 4 and merge its relevant bits into meta recipe 5
[gitmo/Moose.git] / lib / Moose / Cookbook / Meta / Recipe5.pod
1 package Moose::Cookbook::Meta::Recipe5;
2
3 # ABSTRACT: Adding a "table" attribute as a metaclass trait
4
5 __END__
6
7
8 =pod
9
10 =head1 SYNOPSIS
11
12   package MyApp::Meta::Class::Trait::HasTable;
13   use Moose::Role;
14
15   has table => (
16       is  => 'rw',
17       isa => 'Str',
18   );
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
26   __PACKAGE__->meta->table('User');
27
28 =head1 DESCRIPTION
29
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.
33
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.
36
37 =head1 THE METACLASS TRAIT
38
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()>.
44
45 =head2 Using this Metaclass Trait in Practice
46
47
48 Accessing this new C<table> attribute is quite simple. Given a class
49 named C<MyApp::User>, we could simply write the following:
50
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:
57
58   $table = MyApp::User->meta->table
59       if MyApp::User->meta->can('table');
60
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.
64
65 =head1 SEE ALSO
66
67 L<Moose::Cookbook::Meta::Recipe3> - Labels implemented via attribute
68 traits
69
70 =pod