1 package Moose::Cookbook::Meta::Table_MetaclassTrait;
3 # ABSTRACT: Adding a "table" attribute as a metaclass trait
13 package MyApp::Meta::Class::Trait::HasTable;
26 # in lib/MyApp/Meta/Class/Trait/HasTable.pm
27 package MyApp::Meta::Class::Trait::HasTable;
35 package Moose::Meta::Class::Custom::Trait::HasTable;
36 sub register_implementation { 'MyApp::Meta::Class::Trait::HasTable' }
38 # in lib/MyApp/User.pm
40 use Moose -traits => 'HasTable';
42 __PACKAGE__->meta->table('User');
46 In this recipe, we'll create a class metaclass trait which has a "table"
47 attribute. This trait is for classes associated with a DBMS table, as one
50 In this example, the table name is just a string, but in a real ORM
51 the table might be an object describing the table.
53 =head1 THE METACLASS TRAIT
55 This really is as simple as the recipe L</SYNOPSIS> shows. The trick is
56 getting your classes to use this metaclass, and providing some sort of sugar
57 for declaring the table. This is covered in
58 L<Moose::Cookbook::Extending::Debugging_BaseClassRole>, which shows how to
59 make a module like C<Moose.pm> itself, with sugar like C<has_table()>.
61 =head2 Using this Metaclass Trait in Practice
63 Accessing this new C<table> attribute is quite simple. Given a class
64 named C<MyApp::User>, we could simply write the following:
66 my $table = MyApp::User->meta->table;
68 As long as C<MyApp::User> has arranged to apply the
69 C<MyApp::Meta::Class::Trait::HasTable> to its metaclass, this method call just
70 works. If we want to be more careful, we can check that the class metaclass
71 object has a C<table> method:
73 $table = MyApp::User->meta->table
74 if MyApp::User->meta->can('table');
76 In theory, this is not entirely correct, since the metaclass might be getting
77 its C<table> method from a I<different> trait. In practice, you are unlikely
78 to encounter this sort of problem.
82 This recipe doesn't work when you paste it all into a single file. This is
83 because the C<< use Moose -traits => 'HasTable'; >> line ends up being
84 executed before the C<table> attribute is defined.
86 When the two packages are separate files, this just works.
90 L<Moose::Cookbook::Meta::Labeled_AttributeTrait> - Labels implemented via
97 can_ok( MyApp::User->meta, 'table' );
98 is( MyApp::User->meta->table, 'User', 'My::User table is User' );