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