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