Commit | Line | Data |
daa0fd7d |
1 | package Moose::Cookbook::Meta::Recipe4; |
3f002851 |
2 | |
daa0fd7d |
3 | # ABSTRACT: Adding a "table" attribute to the metaclass |
4 | |
5 | __END__ |
3f002851 |
6 | |
3f002851 |
7 | |
daa0fd7d |
8 | =pod |
3f002851 |
9 | |
10 | =head1 SYNOPSIS |
11 | |
12 | package MyApp::Meta::Class; |
13 | use Moose; |
14 | extends 'Moose::Meta::Class'; |
15 | |
6a7e3999 |
16 | has table => ( |
17 | is => 'rw', |
18 | isa => 'Str', |
19 | ); |
3f002851 |
20 | |
21 | =head1 DESCRIPTION |
22 | |
23 | In this recipe, we'll create a new metaclass which has a "table" |
24 | attribute. This metaclass is for classes associated with a DBMS table, |
25 | as one might do for an ORM. |
26 | |
27 | In this example, the table name is just a string, but in a real ORM |
28 | the table might be an object describing the table. |
29 | |
30 | =head1 THE METACLASS |
31 | |
ccea63ce |
32 | This really is as simple as the recipe L</SYNOPSIS> shows. The trick |
33 | is getting your classes to use this metaclass, and providing some sort |
34 | of sugar for declaring the table. This is covered in |
35 | L<Moose::Cookbook::Extending::Recipe2>, which shows how to make a |
6fa0a13f |
36 | module like C<Moose.pm> itself, with sugar like C<has_table()>. |
3f002851 |
37 | |
c5b9daec |
38 | =head2 Using this Metaclass in Practice |
3f002851 |
39 | |
ccea63ce |
40 | Accessing this new C<table> attribute is quite simple. Given a class |
41 | named C<MyApp::User>, we could simply write the following: |
3f002851 |
42 | |
6a7e3999 |
43 | my $table = MyApp::User->meta->table; |
3f002851 |
44 | |
ccea63ce |
45 | As long as C<MyApp::User> has arranged to use C<MyApp::Meta::Class> as |
46 | its metaclass, this method call just works. If we want to be more |
47 | careful, we can check the metaclass's class: |
48 | |
49 | $table = MyApp::User->meta->table |
50 | if MyApp::User->meta->isa('MyApp::Meta::Class'); |
51 | |
52 | =head1 CONCLUSION |
53 | |
54 | Creating custom metaclass is trivial. Using it is a little harder, and |
55 | is covered in other recipes. We will also talk about applying traits |
56 | to a class metaclass, which is a more flexible and cooperative |
57 | implementation. |
3f002851 |
58 | |
59 | =head1 SEE ALSO |
60 | |
61 | L<Moose::Cookbook::Meta::Recipe5> - The "table" attribute implemented |
c5b9daec |
62 | as a metaclass trait |
63 | |
64 | L<Moose::Cookbook::Extending::Recipe2> - Acting like Moose.pm and |
65 | providing sugar Moose-style |
3f002851 |
66 | |
3f002851 |
67 | =pod |