From f134da35ad5716aba168421a00286fb84fb7cefd Mon Sep 17 00:00:00 2001 From: Marcel de Rooy Date: Mon, 24 Nov 2014 13:05:34 +0100 Subject: [PATCH] Bug 13019: Follow-up for find in Koha::Object Content-Type: text/plain; charset=utf-8 This patch includes the proposal to add find as method to Koha::Object too. In the form implemented it supports class and object method calls. The test Borrower.t includes an additional test for this change. Test plan: Run t/Borrower.t and t/db_dependent/Borrower.t and Borrowers.t. Signed-off-by: Marcel de Rooy --- Koha/Object.pm | 26 ++++++++++++++++++++++++++ t/db_dependent/Borrower.t | 11 ++++++++--- 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/Koha/Object.pm b/Koha/Object.pm index ff712c9..c0884c5 100644 --- a/Koha/Object.pm +++ b/Koha/Object.pm @@ -92,6 +92,32 @@ sub _new_from_dbic { } +=head3 find + + my $object = Koha::Object->find( $id ); + + This method allows you to fetch record $id from the database. + It would normally be used as a static (class) method, but it can be + called too as an object method. + It returns a new object or undef if $id is not found. + +=cut + +sub find { + my ( $class_or_self, $id ) = @_; + my $class; + if( ref $class_or_self ) { + $class = $class_or_self->type; + } else { + $class = $class_or_self; + $class =~ s/^Koha:://; + } + my $result = + Koha::Database->new()->schema()->resultset( $class )->find($id); + return if !$result; + return _new_from_dbic( "Koha::$class", $result ); +} + =head3 $object->store(); Saves the object in storage. diff --git a/t/db_dependent/Borrower.t b/t/db_dependent/Borrower.t index 8290cab..4ba38de 100755 --- a/t/db_dependent/Borrower.t +++ b/t/db_dependent/Borrower.t @@ -17,7 +17,7 @@ use Modern::Perl; -use Test::More tests => 13; +use Test::More tests => 14; use Test::Warn; use C4::Context; @@ -49,9 +49,14 @@ is( $object->in_storage, 1, "Object is now stored" ); my $borrowernumber = $object->borrowernumber; -my $borrower = Koha::Database->new()->schema()->resultset('Borrower')->find( $borrowernumber ); +#test find as class method on the stored borrower +my $borrower = Koha::Borrower->find( $borrowernumber ); is( $borrower->surname(), "Test Surname", "Object found in database" ); +#test find as an object method too +is( ref $borrower->find( $borrowernumber ), 'Koha::Borrower', + 'Find as object method works too'); + is( $object->is_changed(), 0, "Object is unchanged" ); $object->surname("Test Surname"); is( $object->is_changed(), 0, "Object is still unchanged" ); @@ -67,7 +72,7 @@ $object->store(); is( $object->is_changed(), 0, "Object no longer marked as changed after being stored" ); $object->delete(); -$borrower = Koha::Database->new()->schema()->resultset('Borrower')->find( $borrowernumber ); +$borrower = Koha::Borrower->find( $borrowernumber ); ok( ! $borrower, "Object no longer found in database" ); is( $object->in_storage, 0, "Object is not in storage" ); -- 1.7.7.6