1 package Moose::Cookbook::Meta::Table_MetaclassTrait;
3 # ABSTRACT: Adding a "table" attribute as a metaclass trait
12 package MyApp::Meta::Class::Trait::HasTable;
20 package Moose::Meta::Class::Custom::Trait::HasTable;
21 sub register_implementation { 'MyApp::Meta::Class::Trait::HasTable' }
24 use Moose -traits => 'HasTable';
26 __PACKAGE__->meta->table('User');
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
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.
37 =head1 THE METACLASS TRAIT
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()>.
45 =head2 Using this Metaclass Trait in Practice
48 Accessing this new C<table> attribute is quite simple. Given a class
49 named C<MyApp::User>, we could simply write the following:
51 my $table = MyApp::User->meta->table;
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:
58 $table = MyApp::User->meta->table
59 if MyApp::User->meta->can('table');
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.
67 L<Moose::Cookbook::Meta::Labeled_AttributeTrait> - Labels implemented via