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;
29 Moose::Util::meta_class_alias('HasTable');
36 # in lib/MyApp/User.pm
38 use Moose -traits => 'HasTable';
40 __PACKAGE__->meta->table('User');
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
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.
51 =head1 THE METACLASS TRAIT
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()>.
59 =head2 Using this Metaclass Trait in Practice
61 Accessing this new C<table> attribute is quite simple. Given a class
62 named C<MyApp::User>, we could simply write the following:
64 my $table = MyApp::User->meta->table;
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:
71 $table = MyApp::User->meta->table
72 if MyApp::User->meta->can('table');
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.
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.
84 When the two packages are separate files, this just works.
88 L<Moose::Cookbook::Meta::Labeled_AttributeTrait> - Labels implemented via
95 can_ok( MyApp::User->meta, 'table' );
96 is( MyApp::User->meta->table, 'User', 'My::User table is User' );