r31712@martha (orig r1247): groditi | 2009-10-02 17:02:01 -0400
[catagits/Reaction.git] / lib / Reaction / UI / Controller / Role / GetCollection.pm
1 package Reaction::UI::Controller::Role::GetCollection;
2
3 use Moose::Role -traits => 'MethodAttributes';
4
5 has model_name => (isa => 'Str', is => 'rw', required => 1);
6 has collection_name => (isa => 'Str', is => 'rw', required => 1);
7
8 sub get_collection {
9   my ($self, $c) = @_;
10   my $model = $c->model( $self->model_name );
11   confess "Failed to find Catalyst model named: " . $self->model_name
12     unless $model;
13   my $collection = $self->collection_name;
14   if( my $meth = $model->can( $collection ) ){
15     return $model->$meth;
16   } elsif ( my $meta = $model->can('meta') ){
17     if ( my $attr = $model->$meta->find_attribute_by_name($collection) ) {
18       my $reader = $attr->get_read_method;
19       return $model->$reader;
20     }
21   }
22   confess "Failed to find collection $collection";
23 }
24
25 1;
26
27 __END__;
28
29 =head1 NAME
30
31 Reaction::UI::Controller::Role::GetCollection
32
33 =head1 DESCRIPTION
34
35 Provides a C<get_collection> method, which fetches an C<Collection> object
36 from a specified model.
37
38 =head1 SYNOPSYS
39
40     package MyApp::Controller::Foo;
41
42     use base 'Reaction::Controller';
43     use Reaction::Class;
44
45     with 'Reaction::UI::Controller::Role::GetCollection';
46
47     __PACKAGE__->config( model_name => 'MyAppIM', collection_name => 'foos' );
48
49     sub bar :Local {
50       my($self, $c) = @_;
51       my $obj = $self->get_collection($c)->find( $some_key );
52     }
53
54 =head1 ATTRIBUTES
55
56 =head2 model_name
57
58 The name of the model this controller will use as it's data source. Should be a
59 name that can be passed to C<$C-E<gt>model>
60
61 =head2 collection_name
62
63 The name of the collection whithin the model that this Controller will be
64 utilizing.
65
66 =head1 METHODS
67
68 =head2 get_collection $c
69
70 Returns an instance of the collection this controller uses.
71
72 =head1 SEE ALSO
73
74 =over4
75
76 =item L<Reaction::UI::Controller>
77
78 =item L<Reaction::UI::Controller::Role::Action::Simple>
79
80 =item L<Reaction::UI::Controller::Role::Action::Object>
81
82 =item L<Reaction::UI::Controller::Role::Action::List>
83
84 =item L<Reaction::UI::Controller::Role::Action::View>
85
86 =item L<Reaction::UI::Controller::Role::Action::Create>
87
88 =item L<Reaction::UI::Controller::Role::Action::Update>
89
90 =item L<Reaction::UI::Controller::Role::Action::Delete>
91
92 =item L<Reaction::UI::Controller::Role::Action::DeleteAll>
93
94 =back
95
96 =head1 AUTHORS
97
98 See L<Reaction::Class> for authors.
99
100 =head1 LICENSE
101
102 See L<Reaction::Class> for the license.
103
104 =cut