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