| 1 | package DBIx::Quick::Converter; | ||
| 2 | |||
| 3 | use v5.16.3; | ||
| 4 | use strict; | ||
| 5 | use warnings; | ||
| 6 | |||
| 7 | use Moo::Role; | ||
| 8 | |||
| 9 | requires 'to_db'; | ||
| 10 | requires 'from_db'; | ||
| 11 | |||
| 12 | 1; | ||
| 13 | =head1 NAME | ||
| 14 | |||
| 15 | DBIx::Quick::Converter - Role to convert fields after database recover and before inserts and updates. | ||
| 16 | |||
| 17 | =head1 SYNOPSIS | ||
| 18 | |||
| 19 | package MyApp::DB::Converters::DateTime; | ||
| 20 | |||
| 21 | use strict; | ||
| 22 | use warnings; | ||
| 23 | |||
| 24 | use Moo; | ||
| 25 | |||
| 26 | use DateTime::Format::Pg; | ||
| 27 | |||
| 28 | sub to_db { | ||
| 29 | shift; | ||
| 30 | my $dt = shift; | ||
| 31 | return undef if !$dt; | ||
| 32 | return DateTime::Format::Pg->new->format_datetime($dt); | ||
| 33 | } | ||
| 34 | |||
| 35 | sub from_db { | ||
| 36 | shift; | ||
| 37 | my $date = shift; | ||
| 38 | return undef if !$date; | ||
| 39 | return DateTime::Format::Pg->new->parse_datetime($date); | ||
| 40 | } | ||
| 41 | |||
| 42 | with 'DBIx::Quick::Converter'; | ||
| 43 | |||
| 44 | =head1 DESCRIPTION | ||
| 45 | |||
| 46 | This is Moo role that must be implemented by objects sent to the C<converter> attribute of the C<field> declaration in L<DBIx::Quick>. | ||
| 47 | |||
| 48 | =head1 METHODS NEEDED TO BE IMPLEMENTED | ||
| 49 | |||
| 50 | =head2 to_db | ||
| 51 | |||
| 52 | The subroutine that transforms data into the format which you want to store in the database. | ||
| 53 | |||
| 54 | Takes one argument. | ||
| 55 | |||
| 56 | =head2 from_db | ||
| 57 | |||
| 58 | The subroutine that transforms the database data into your wanted format in perl, for example a L<DateTime> object. | ||
| 59 | |||
| 60 | Takes one argument. | ||
| 61 | |||
| 62 | =cut |