Use a metaclass trait and don't do "also => Moose"
[gitmo/Moose.git] / lib / Moose / Cookbook / Extending / Recipe4.pod
1 package Moose::Cookbook::Extending::Recipe4;
2
3 # ABSTRACT: Acting like Moose.pm and providing sugar Moose-style
4
5 __END__
6
7
8 =pod
9
10 =head1 SYNOPSIS
11
12   package MyApp::Mooseish;
13
14   use Moose::Exporter;
15
16   Moose::Exporter->setup_import_methods(
17       with_meta       => ['has_table'],
18       class_metaroles => {
19           class => ['MyApp::Meta::Class::Trait::HasTable'],
20       },
21   );
22
23   sub has_table {
24       my $meta = shift;
25       $meta->table(shift);
26   }
27
28   package MyApp::Meta::Class::Trait::HasTable;
29   use Moose::Role;
30
31   has table => (
32       is  => 'rw',
33       isa => 'Str',
34   );
35
36 =head1 DESCRIPTION
37
38 This recipe expands on the use of L<Moose::Exporter> we saw in
39 L<Moose::Cookbook::Extending::Recipe1> and the class metaclass trait we saw in
40 L<Moose::Cookbook::Meta::Recipe5>. In this example we provide our own
41 metaclass trait, and we also export a C<has_table> sugar function.
42
43 The C<with_meta> parameter specifies a list of functions that should
44 be wrapped before exporting. The wrapper simply ensures that the
45 importing package's appropriate metaclass object is the first argument
46 to the function, so we can do C<S<my $meta = shift;>>.
47
48 See the L<Moose::Exporter> docs for more details on its API.
49
50 =head1 USING MyApp::Mooseish
51
52 The purpose of all this code is to provide a Moose-like
53 interface. Here's what it would look like in actual use:
54
55   package MyApp::User;
56
57   use namespace::autoclean;
58
59   use Moose;
60   use MyApp::Mooseish;
61
62   has_table 'User';
63
64   has 'username' => ( is => 'ro' );
65   has 'password' => ( is => 'ro' );
66
67   sub login { ... }
68
69 =head1 CONCLUSION
70
71 Providing sugar functions can make your extension look much more
72 Moose-ish. See L<Fey::ORM> for a more extensive example.
73
74 =begin testing
75
76
77 {
78     package MyApp::User;
79
80     MyApp::Mooseish->import;
81
82     has_table( 'User' );
83
84     has( 'username' => ( is => 'ro' ) );
85     has( 'password' => ( is => 'ro' ) );
86
87     sub login { }
88 }
89
90 isa_ok( MyApp::User->meta, 'MyApp::Meta::Class' );
91 is( MyApp::User->meta->table, 'User',
92     'MyApp::User->meta->table returns User' );
93 ok( MyApp::User->can('username'),
94     'MyApp::User has username method' );
95
96 =end testing
97
98 =pod