Merged dkubb's Module::Find code into Schema->load_classes
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Schema.pm
1 package DBIx::Class::Schema;
2
3 use strict;
4 use warnings;
5
6 use base qw/Class::Data::Inheritable/;
7 use base qw/DBIx::Class/;
8
9 __PACKAGE__->load_components(qw/Exception/);
10 __PACKAGE__->mk_classdata('class_registrations' => {});
11
12 =head1 NAME
13
14 DBIx::Class::Schema - composable schemas
15
16 =head1 SYNOPSIS
17
18   in My/Schema.pm
19
20   package My::Schema;
21
22   use base qw/DBIx::Class::Schema/;
23
24   __PACKAGE__->load_classes(qw/Foo Bar Baz/);
25
26   in My/Schema/Foo.pm
27
28   package My::Schema::Foo;
29
30   use base qw/DBIx::Class::Core/;
31
32   __PACKAGE__->table('foo');
33   ...
34
35   in My/DB.pm
36
37   use My::Schema;
38
39   My::Schema->compose_connection('My::DB', $dsn, $user, $pass, $attrs);
40
41   then in app code
42
43   my @obj = My::DB::Foo->search({}); # My::DB::Foo isa My::Schema::Foo My::DB
44
45 =head1 DESCRIPTION
46
47 =head1 METHODS
48
49 =over 4
50
51 =cut
52
53 sub register_class {
54   my ($class, $name, $to_register) = @_;
55   my %reg = %{$class->class_registrations};
56   $reg{$name} = $to_register;
57   $class->class_registrations(\%reg);
58 }
59
60 sub registered_classes {
61   return values %{shift->class_registrations};
62 }
63
64 sub load_classes {
65   my $class = shift;
66   my @comp = grep { $_ !~ /^#/ } @_;
67   unless (@comp) {
68     eval "require Module::Find;";
69     $class->throw("No arguments to load_classes and couldn't load".
70       " Module::Find ($@)") if $@;
71     @comp = map { substr $_, length "${class}::"  }
72               Module::Find::findallmod($class);
73   }
74   foreach my $comp (@comp) {
75     my $comp_class = "${class}::${comp}";
76     eval "use $comp_class";
77     die $@ if $@;
78     $class->register_class($comp => $comp_class);
79   }
80 }
81
82 sub compose_connection {
83   my ($class, $target, @info) = @_;
84   $class->setup_connection_class($target, @info);
85   my %reg = %{ $class->class_registrations };
86   while (my ($comp, $comp_class) = each %reg) {
87     my $target_class = "${target}::${comp}";
88     $class->inject_base($target_class, $comp_class, $target);
89   }
90 }
91
92 sub setup_connection_class {
93   my ($class, $target, @info) = @_;
94   $class->inject_base($target => 'DBIx::Class');
95   $target->load_components('DB');
96   $target->connection(@info);
97 }
98
99 sub inject_base {
100   my ($class, $target, @to_inject) = @_;
101   {
102     no strict 'refs';
103     unshift(@{"${target}::ISA"}, @to_inject);
104   }
105 }
106
107 1;
108
109 =back
110
111 =head1 AUTHORS
112
113 Matt S. Trout <perl-stuff@trout.me.uk>
114
115 =head1 LICENSE
116
117 You may distribute this code under the same terms as Perl itself.
118
119 =cut
120