Objects.pm

filter: Statementstmt 88.2% 98 / 111 Branchbran 66.6% 24 / 36 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 94.4% 17 / 18 Podpod 100% 2 / 2 totaltotal 84.4% 141 / 167 CC 28 SCAR 12.0
CC
28
Cov
83%
load_objects
7.1
__ANON__
4.4
find
4.4
CRAP 3.3
↑ Summary Objects/Base.pm »
1 package DBIx::Class::Objects;
2  
3 4 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 4 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 # using this because it will be applied to result classes, not because we want
7 # to import this behavior
8 4 ▶use DBIx::Class::Objects::Role::Result ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 4 ▶use Class::Load 'try_load_class';
Subroutine BEGIN: called CC=1 SCAR=0.0
11 4 ▶use namespace::autoclean;
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 4 our $VERSION = '0.02';
14  
15 4 has 'schema' => (
16 is => 'ro',
17 isa => 'DBIx::Class::Schema',
18 required => 1,
19 );
20  
21 4 has 'debug' => (
22 is => 'rw',
23 isa => 'Bool',
24 default => 0,
25 );
26  
27 4 has 'base_class' => (
28 is => 'ro',
29 isa => 'Str',
30 required => 1,
31 default => 'DBIx::Class::Objects::Base',
32 );
33  
34 4 has 'result_role' => (
35 is => 'ro',
36 isa => 'Str',
37 required => 1,
38 default => 'DBIx::Class::Objects::Role::Result',
39 );
40  
41 4 has 'object_base' => (
42 is => 'rw',
43 isa => 'Str',
44 required => 0, # XXX Fix this later
45 writer => '_set_object_base',
46 );
47  
48 around 'BUILDARGS' => sub {
49 3 ▶ my $orig = shift;
Subroutine __ANON__: called CC=2 SCAR=7.0
50 3 my $self = shift;
51 3 ▶ my %args = ref $_[0] ? %{$_[0]} : @_;
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] ? : 3 0 3
52 3 $args{object_base} =~ s/::$//;
53 3 $self->$orig(\%args);
54 4 };
55  
56 sub _get_object_class_name {
57 52 ▶ my ( $self, $source_name ) = @_;
Subroutine _get_object_class_name: called CC=1 SCAR=0.0
58 52 return $self->object_base . '::' . $source_name;
59 }
60  
61 sub objectset {
62 7 ▶ my ( $self, $source_name ) = @_;
Subroutine objectset: called CC=1 SCAR=0.0
Pod documented
63  
64 7 return $self->_create_object_set(
65 $self->schema->resultset($source_name) );
66 }
67  
68 sub _create_object_set {
69  
70 # this method allows the user to ensure that resultsets contain instances
71 # of DBIx::Class::Objects instead of DBIx::Class::Result
72 9 ▶ my ( $self, $resultset ) = @_;
Subroutine _create_object_set: called CC=2 SCAR=7.6
73  
74 9 my %methods;
75 9 foreach my $method (qw/find next/) {
76  
77 # Haven't debugged this, but simply declaring a single subroutine and
78 # assigning it to the keys doesn't work. You get errors like this:
79 #
80 # DBIx::Class::ResultSet::find(): find() expects either a column/value
81 # hashref, or a list of values corresponding to the columns of the
82 # specified unique constraint 'primary' at t/resultset.t line 30
83 #
84 # Doing it this way results in a fresh copy of the subref for every
85 # method at a slight performance cost. Caching bug?
86 $methods{$method} = sub {
87 5 ▶ my $this = shift;
Subroutine __ANON__: called CC=4 SCAR=14.8
Subroutine find: called CC=4 SCAR=14.8
88 5 ▶ my $result = $this->next::method(@_) or return;
Branch: 2 branches
BranchTrueFalseTotal
my $result = $this->next::method(@_) or return 1 4 5
my $result = $this->next::method(@_) or return 2 8 10
89 4 my $source_name = $result->result_source->source_name;
90 4 ▶ unless ($source_name) {
Branch: 2 branches
BranchTrueFalseTotal
unless ($source_name) 0 4 4
unless ($source_name) 0 8 8
91 0 my $type = ref $result;
92 0 croak("Panic: Couldn't determine source name in '$method' for '$type'");
93 }
94 4 ▶ my $object_class = $self->_get_object_class_name($source_name)
Branch: 2 branches
BranchTrueFalseTotal
my $object_class = $self->_get_object_class_name($source_name) or croak("Panic: Couldn't determine object class in '${method}' for '${source_name}'") 0 4 4
my $object_class = $self->_get_object_class_name($source_name) or croak("Panic: Couldn't determine object class in '${method}' for '${source_name}'") 0 8 8
95 or croak(
96 "Panic: Couldn't determine object class in '$method' for '$source_name'");
97 4 return $object_class->new( { result_source => $result } );
98 18 };
99 }
100  
101 # we do it this way because they might have created a custom
102 # resultset class and thus, we don't know *which* class we're inheriting
103 # from.
104 my $meta = Moose::Meta::Class->create_anon_class(
105 superclasses => [ ref $resultset ],
106 cache => 1,
107 methods => {
108 %methods,
109 all => sub {
110 1 ▶ my $this = shift;
Subroutine __ANON__: called CC=2 SCAR=10.0
Subroutine all: not called CC=2 SCAR=10.0
111 1 my @all = $this->next::method(@_);
112 1 ▶ return unless @all;
Branch: 2 branches
BranchTrueFalseTotal
unless @all 0 1 1
unless @all 0 0 0
113 1 my $object_class = $self->_get_object_class_name(
114 $all[0]->result_source->source_name );
115 return
116 1 map { $object_class->new( { result_source => $_ } ) } @all;
117 },
118 },
119 9 );
120 9 $meta->rebless_instance($resultset);
121 9 return $resultset;
122 }
123  
124 sub load_objects {
125 3 ▶ my $self = shift;
Subroutine load_objects: called CC=7 SCAR=19.7
Pod documented
126 3 my $schema = $self->schema;
127  
128 3 foreach my $source_name ($schema->sources) {
129 15 my $object_class = $self->_get_object_class_name($source_name);
130  
131 15 $self->_debug("Trying to load $object_class");
132  
133 15 ▶ if ( try_load_class($object_class) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (try_load_class($object_class)) { } 6 9 15
134 6 $self->_debug("\t$object_class found.");
135 }
136 else {
137 9 $self->_debug("\t$object_class not found. Building.");
138 9 Moose::Meta::Class->create(
139 $object_class,
140 superclasses => [ $self->base_class ],
141 );
142 9 ▶ unless ( Class::Load::is_class_loaded($object_class) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (Class::Load::is_class_loaded($object_class)) 0 9 9
143 0 die "$object_class didn't load";
144 }
145 }
146  
147 # XXX Not sure about this. If they forget to inherit from
148 # DBIx::Class::Objects::Base, we do it for them. It works around an
149 # issue the programmer might forget, but is this too much magic, given
150 # that we're already doing a lot of it?
151 15 my $meta = $object_class->meta;
152 15 my $was_immutable = $meta->is_immutable;
153 15 ▶ $meta->make_mutable if $was_immutable;
Branch: 1 branch
BranchTrueFalseTotal
if $was_immutable 6 9 15
154 15 ▶ unless ( $object_class->isa( $self->base_class ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($object_class->isa($self->base_class)) 0 15 15
155 0 $meta->superclasses( $meta->superclasses, $self->base_class );
156 }
157 15 $self->_add_methods( $object_class, $source_name );
158 15 ▶ $meta->make_immutable if $was_immutable;
Branch: 1 branch
BranchTrueFalseTotal
if $was_immutable 6 9 15
159 }
160 }
161  
162 sub _add_methods {
163 15 ▶ my ( $self, $class, $source_name ) = @_;
Subroutine _add_methods: called CC=3 SCAR=11.0
164 15 my $schema = $self->schema;
165 15 my $meta = $class->meta;
166  
167 15 my $source = $schema->resultset($source_name)->result_source;
168  
169 15 $self->result_role->meta->apply(
170 $meta,
171 handles => [ $source->columns ],
172 result_source_class => $source->result_class,
173 source => $class,
174 );
175  
176 15 my @relationships = $source->relationships;
177 15 foreach my $relationship (@relationships) {
178 24 my $info = $source->relationship_info($relationship);
179  
180 # if the accessor is a "multi" access, it returns a resultset, not a
181 # result.
182 24 my $is_multi = 'multi' eq $info->{attrs}{accessor};
183 my $source
184 24 = $schema->resultset( $info->{source} )->result_source->source_name;
185 24 my $other_class = $self->_get_object_class_name($source);
186  
187 # XXX Bless me father for I have sinned ...
188 24 $info->{_result_class_to_object_class} = $other_class;
189  
190 24 ▶ if ($is_multi) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_multi) { } 9 15 24
191  
192 # all resultsets get blessed into our resultset class
193 $meta->add_method(
194 $relationship => sub {
195 2 ▶ my $this = shift;
Subroutine __ANON__: called CC=2 SCAR=7.1
196 2 ▶ my $resultset = $this->result_source->$relationship(@_)
Branch: 1 branch
BranchTrueFalseTotal
my $resultset = $this->result_source->$relationship(@_) or return 0 2 2
197 or return;
198 2 return $self->_create_object_set($resultset);
199 },
200 9 );
201 }
202 else {
203 # all results are our objects, not results
204 $meta->add_method(
205 $relationship => sub {
206 19 ▶ my $this = shift;
Subroutine __ANON__: called CC=2 SCAR=6.9
207 19 ▶ my $response = $this->result_source->$relationship
Branch: 1 branch
BranchTrueFalseTotal
my $response = $this->result_source->$relationship or return 1 18 19
208 or return;
209 18 return $other_class->new(
210 { result_source => $response } );
211 }
212 15 );
213 }
214 }
215 }
216  
217 sub _debug {
218 30 ▶ my ( $self, $message ) = @_;
Subroutine _debug: called CC=2 SCAR=8.1
219 30 ▶ return unless $self->debug;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->debug 30 0 30
220 0 warn "$message\n";
221 }
222  
223 4 __PACKAGE__->meta->make_immutable;
224  
225 4 1;
226  
227 __END__
228  
229 =head1 NAME
230  
231 DBIx::Class::Objects - Rewrite your DBIC objects via inheritance
232  
233 =head1 VERSION
234  
235 0.02
236  
237 =head1 SYNOPSIS
238  
239 my $schema = My::DBIx::Class::Schema->connect(@args);
240  
241 my $objects = DBIx::Class::Objects->new({
242 schema => $schema,
243 object_base => 'My::Object',
244 });
245 $objects->load_objects;
246  
247 my $person = $objects->objectset('Person')
248 ->find( { email => 'not@home.com' } );
249  
250 # If found, $person is a My::Object::Person object, not a
251 # My::DBIx::Class::Schema::Result::Person
252  
253 =head1 WARNING
254  
255 The C<DBIx::Class::Objects> module is an experiment to "fix" (for some values
256 of "fix") some issues we traditionally have with ORMs by allowing the
257 programmer to use easily use objects as they wish to rather than the hierarchy
258 forced on them by C<DBIx::Class>.
259  
260 This is B<ALPHA> code and may be a very bad idea. Use at your own risk.
261  
262 =head1 DESCRIPTION
263  
264 Consider a database where you have people and each person might be a customer.
265 The following two tables might demonstrate that relationship.
266  
267 CREATE TABLE people (
268 person_id INTEGER PRIMARY KEY AUTOINCREMENT,
269 name VARCHAR(255) NOT NULL,
270 email VARCHAR(255) NULL UNIQUE,
271 birthday DATETIME NOT NULL
272 );
273  
274 CREATE TABLE customers (
275 customer_id INTEGER PRIMARY KEY AUTOINCREMENT,
276 person_id INTEGER NOT NULL UNIQUE,
277 first_purchase DATETIME NOT NULL,
278 FOREIGN KEY(person_id) REFERENCES people(person_id)
279 );
280  
281 If your schema starts with C<Sample::Schema::>, in C<DBIx::Class> terms you'll
282 find that C<Sample::Schema::Result::Person> I<might_have> a
283 C<Sample::Schema::Result::Customer>:
284  
285 __PACKAGE__->might_have(
286 "customer",
287 "Sample::Schema::Result::Customer",
288 { "foreign.person_id" => "self.person_id" },
289 );
290  
291 As a programmer, you might find that frustrating. From your viewpoint, you
292 might think that C<Customer> I<isa> C<Person>. Or perhaps you also have
293 C<Employee>s in your database and a person can be both a customer and an
294 employee, how do you model that? For C<DBIx::Class>, you have delegation:
295  
296 my $customer = $person->customer;
297 my $employee = $person->employee;
298  
299 Whereas for OO code, you might want to have a C<Person> class and C<Employee>
300 and C<Customer> roles. Or maybe you're a fan of multiple inheritance (I hope
301 not) and you create a C<CustomerEmployee> class which tries to inherit from
302 both C<Customer> and C<Employee>.
303  
304 Not having full control over your object hierarchy is merely one of the
305 problems with the L<Object-Relational Impedence Mismatch|http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch>.
306  
307 Or maybe you're dismayed to instantiate a C<Sample::Schema::Result::Person>
308 object and discover that you have 157 methods because you were forced to
309 inherit from C<DBIx::Class::Core>, when all you wanted was the name, email and
310 birthday. This experiment tries to minimize that.
311  
312 =head1 METHODS
313  
314 =head2 C<new>
315  
316 my $objects = DBIx::Class::Objects->new({
317 schema => $schema,
318 object_base => 'My::Object',
319 });
320  
321 The C<new> constructor takes two required arguments and one optional argument:
322  
323 =over 4
324  
325 =item * C<schema> (required)
326  
327 A C<DBIx::Class::Schema> object.
328  
329 =item * C<object_base> (required)
330  
331 The package prefix of your name objects. If your schema classes resemble
332 something like C<Sample::Schema::Result::Person>, your returned objects will
333 have names like C<My::Object::Person> (assuming you used C<My::Object> for the
334 C<object_base> parameter).
335  
336 =item * C<debug> (optional)
337  
338 At the present time, this will print to STDERR a list of objects you're trying
339 to build and whether or not a concrete implementation was found or it's being
340 built on the fly.
341  
342 Trying to load My::Object::Person
343 My::Object::Person found.
344 Trying to load My::Object::Order
345 My::Object::Order not found. Building.
346 Trying to load My::Object::Customer
347 My::Object::Customer found.
348 Trying to load My::Object::Item
349 My::Object::Item not found. Building.
350 Trying to load My::Object::OrderItem
351 My::Object::OrderItem not found. Building.
352  
353 =back
354  
355 =head2 C<load_objects>
356  
357 $objects->load_objects;
358  
359 Similar to L<DBIx::Class::Schema>'s C<load_namespaces>, but it's an instane
360 method instead of a class method. It will load all of your objects for you. It
361 will ensure that your objects inherit from L<DBIx::Class::Objects::Base> and
362 will apply the parameterized role L<DBIx::Class::Objects::Role::Result>.
363  
364 The base class is what allows things like C<update> to be called directly on
365 the object. Is is the parameterized role which sets up the delegation to the
366 C<DBIx::Class> objects.
367  
368 =head2 C<objectset>
369  
370 my $person = $objects->objectset('Person')
371 ->find( { email => 'not@home.com' } );
372  
373 This method is similar to C<< $schema->resultset >>, but it returns sets of
374 C<DBIx::Class::Objects> objects instead of results. The interface is the same
375 as C<DBIx::Class::ResultSet>, but calling methods like C<find>, C<next>,
376 C<first>, C<all> and so on should I<do the right thing> (famous last words).
377  
378 =head1 LET'S DELEGATE TO DBIx::Class RESULTS
379  
380 C<DBIx::Class::Objects> is an attempt to allow you to recompose your
381 C<DBIx::Class> objects as you would like. Instead of C<DBIx::Class> returning
382 resultsets and results, C<DBIx::Class::Objects> returns objectsets and
383 objects. You can do anything you want with the latter.
384  
385 =head2 Basic Usage
386  
387 Using this module is as simple as this:
388  
389 my $schema = Sample::Schema->connect(@args);
390  
391 my $objects = DBIx::Class::Objects->new({
392 schema => $schema,
393 object_base => 'My::Object',
394 });
395 $objects->load_objects;
396  
397 my $person = $objects->objectset('Person')
398 ->find( { email => 'not@home.com' } );
399  
400 And you'll discover that you get back a C<My::Object::Person> object instead
401 of a C<Sample::Schema::Result::Person> object. In C<DBIx::Class>, if you don't
402 explicitly create resultset classes, a default resultset class will be created
403 for you. In C<DBIx::Class::Objects>, if you don't explicitly create object
404 classes, a default one is created for you. For example, if you don't have a
405 C<My::Object::Person> class written (or if C<DBIx::Class::Objects> can't find
406 it), you will have a basic C<My::Object::Person> instance with the following
407 methods (according to the debugger):
408  
409 DB<2> m $person
410 BUILD
411 _my_object_person
412 birthday
413 customer
414 email
415 meta
416 name
417 person_id
418 result_source
419 update
420 via DBIx::Class::Objects::Base: DESTROY
421 via DBIx::Class::Objects::Base: new
422 via DBIx::Class::Objects::Base -> Moose::Object: BUILDALL
423 via DBIx::Class::Objects::Base -> Moose::Object: BUILDARGS
424 via DBIx::Class::Objects::Base -> Moose::Object: DEMOLISHALL
425 via DBIx::Class::Objects::Base -> Moose::Object: DOES
426 via DBIx::Class::Objects::Base -> Moose::Object: does
427 via DBIx::Class::Objects::Base -> Moose::Object: dump
428 via UNIVERSAL: VERSION
429 via UNIVERSAL: can
430 via UNIVERSAL: isa
431  
432 That's actually not too bad, compared to C<DBIx::Class>. If you remove
433 C<UNIVERSAL> methods and methods in ALL CAPS, you get this:
434  
435 _my_object_person
436 birthday
437 customer
438 email
439 meta
440 name
441 person_id
442 result_source
443 update
444 via DBIx::Class::Objects::Base: new
445 via DBIx::Class::Objects::Base -> Moose::Object: does
446 via DBIx::Class::Objects::Base -> Moose::Object: dump
447  
448 That's actually a fairly clean object. The C<person_id>, C<email>, C<name> and
449 C<birthday> objects are handled by the C<result_source>. If you want to update
450 the object, you do this:
451  
452 $person->name($new_name);
453 $person->update;
454  
455 =head2 Creating your own objects
456  
457 Having these objects spring up automatically is great and if you have 100
458 result sources, it's nice that you don't have to write 100 object classes.
459 However, though you have far fewer methods, what's the point?
460  
461 Well, you can write your own classes:
462  
463 package My::Object::Person;
464  
465 use Moose;
466 use namespace::autoclean;
467  
468 # this is optional. If you forget to include it, DBIx::Class::Objects will
469 # inject this for you. However, it's good to have it here for
470 # documentation purposes.
471 extends 'DBIx::Class::Objects::Base';
472  
473 sub is_customer {
474 my $self = shift;
475 return defined $self->customer;
476 }
477  
478 __PACKAGE__->meta->make_immutable;
479  
480 1;
481  
482 Again, that's not much of a win, but what if you want inheritance?
483  
484 package My::Object::Customer;
485  
486 use Moose;
487 extends 'My::Object::Person';
488  
489 __PACKAGE__->meta->make_immutable;
490  
491 1;
492  
493 You've now inherited the delegated methods from C<My::Object::Person>.
494  
495 my $customer_os = $objects->objectset('Customer')->search(
496 \%dbix_class_search_args
497 );
498 foreach my $customer ($customer_os->next) {
499 if ( $some_condition ) {
500 $customer->name('new name');
501 $customer->update; # updates $customer->person, too
502 }
503 }
504  
505 For every object, calling C<result_source> gets you the original
506 C<DBIx::Class::Result>.
507  
508 say $customer->result_source; # Sample::Schema::Result::Customer
509 say $customer->person->result_source; # Sample::Schema::Result::Person
510  
511 =head1 AUTHOR
512  
513 Curtis "Ovid" Poe, C<< <ovid at cpan.org> >>
514  
515 =head1 BUGS
516  
517 Please report any bugs or feature requests to C<bug-object-bridge at
518 rt.cpan.org>, or through the web interface at
519 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=DBIx-Class-Objects>. I will be
520 notified, and then you'll automatically be notified of progress on your bug as
521 I make changes.
522  
523 =head1 SUPPORT
524  
525 You can find documentation for this module with the perldoc command.
526  
527 perldoc DBIx::Class::Objects
528  
529 You can also look for information at:
530  
531 =over 4
532  
533 =item * RT: CPAN's request tracker (report bugs here)
534  
535 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=DBIx-Class-Objects>
536  
537 =item * AnnoCPAN: Annotated CPAN documentation
538  
539 L<http://annocpan.org/dist/DBIx-Class-Objects>
540  
541 =item * CPAN Ratings
542  
543 L<http://cpanratings.perl.org/d/DBIx-Class-Objects>
544  
545 =item * Search CPAN
546  
547 L<http://search.cpan.org/dist/DBIx-Class-Objects/>
548  
549 =back
550  
551  
552 =head1 ACKNOWLEDGEMENTS
553  
554  
555 =head1 LICENSE AND COPYRIGHT
556  
557 Copyright 2014 Curtis "Ovid" Poe.
558  
559 This program is free software; you can redistribute it and/or modify it
560 under the terms of the the Artistic License (2.0). You may obtain a
561 copy of the full license at:
562  
563 L<http://www.perlfoundation.org/artistic_license_2_0>
564  
565 Any use, modification, and distribution of the Standard or Modified
566 Versions is governed by this Artistic License. By using, modifying or
567 distributing the Package, you accept this license. Do not use, modify,
568 or distribute the Package, if you do not accept this license.
569  
570 If your Modified Version has been derived from a Modified Version made
571 by someone other than you, you are nevertheless required to ensure that
572 your Modified Version complies with the requirements of this license.
573  
574 This license does not grant you the right to use any trademark, service
575 mark, tradename, or logo of the Copyright Holder.
576  
577 This license includes the non-exclusive, worldwide, free-of-charge
578 patent license to make, have made, use, offer to sell, sell, import and
579 otherwise transfer the Package with respect to any patent claims
580 licensable by the Copyright Holder that are necessarily infringed by the
581 Package. If you institute patent litigation (including a cross-claim or
582 counterclaim) against any party alleging that the Package constitutes
583 direct or contributory patent infringement, then this Artistic License
584 to you shall terminate on the date that such litigation is filed.
585  
586 Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER
587 AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES.
588 THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
589 PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY
590 YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR
591 CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR
592 CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE,
593 EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
↑ Summary Objects/Base.pm »