add alt. hook to PerRequestSchema trait
[catagits/Catalyst-Model-DBIC-Schema.git] / lib / Catalyst / TraitFor / Model / DBIC / Schema / PerRequestSchema.pm
CommitLineData
79ac28c6 1package Catalyst::TraitFor::Model::DBIC::Schema::PerRequestSchema;
63dcfadb 2
2a9509a4 3use Moose::Role;
566a0bca 4use MooseX::MarkAsMethods autoclean => 1;
79ac28c6 5
6with 'Catalyst::Component::InstancePerContext';
7
63dcfadb 8=head1 NAME
9
10Catalyst::TraitFor::Model::DBIC::Schema::PerRequestSchema - Clone the schema
11with attributes for each requests
12
13=head1 SYNOPSIS
14
15 __PACKAGE__->config({
16 traits => ['PerRequestSchema'],
17 });
18
566a0bca 19 sub per_request_schema_attributes {
20 my ($self, $c) = @_;
63dcfadb 21 return (restricting_object => $c->user->obj);
22 }
566a0bca 23 ### OR ###
24 sub per_request_schema {
25 my ($self, $c) = @_;
26 return $self->schema->schema_method($c->user->obj)
27 }
28
63dcfadb 29
30=head1 DESCRIPTION
31
32Clones the schema for each new request with the attributes retrieved from your
33C<per_request_schema_attributes> method, which you must implement. This method
34is passed the context.
35
566a0bca 36Alternatively, you could also override the C<per_request_schema> method if you
37need access to the schema clone and/or need to separate out the Model/Schema
38methods. (See examples above and the defaults in the code.)
39
63dcfadb 40=cut
41
79ac28c6 42sub build_per_context_instance {
43 my ( $self, $ctx ) = @_;
44 return $self unless blessed($ctx);
45
46 my $new = bless {%$self}, ref $self;
47
566a0bca 48 $new->schema($new->per_request_schema($ctx));
79ac28c6 49
50 return $new;
51}
52
566a0bca 53# Thanks to Matt Trout for this idea
54sub per_request_schema {
55 my ($self, $c) = @_;
56 return $self->schema->clone($self->per_request_schema_attributes($c));
57}
58
59### TODO: This should probably be more elegant ###
60sub per_request_schema_attributes {
61 confess "Either per_request_schema_attributes needs to be created, or per_request_schema needs to be overridden!";
62}
63
64
63dcfadb 65=head1 SEE ALSO
66
67L<Catalyst::Model::DBIC::Schema>, L<DBIx::Class::Schema>
68
69=head1 AUTHOR
70
71See L<Catalyst::Model::DBIC::Schema/AUTHOR> and
72L<Catalyst::Model::DBIC::Schema/CONTRIBUTORS>.
73
74=head1 COPYRIGHT
75
76See L<Catalyst::Model::DBIC::Schema/COPYRIGHT>.
77
78=head1 LICENSE
79
80This program is free software, you can redistribute it and/or modify it
81under the same terms as Perl itself.
82
83=cut
84
851;