Merged dkubb's Module::Find code into Schema->load_classes
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Schema.pm
CommitLineData
a02675cd 1package DBIx::Class::Schema;
2
3use strict;
4use warnings;
5
6use base qw/Class::Data::Inheritable/;
41a6f8c0 7use base qw/DBIx::Class/;
a02675cd 8
41a6f8c0 9__PACKAGE__->load_components(qw/Exception/);
74b92d9a 10__PACKAGE__->mk_classdata('class_registrations' => {});
a02675cd 11
c2da098a 12=head1 NAME
13
14DBIx::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
656796f2 43 my @obj = My::DB::Foo->search({}); # My::DB::Foo isa My::Schema::Foo My::DB
c2da098a 44
45=head1 DESCRIPTION
46
47=head1 METHODS
48
49=over 4
50
51=cut
52
a02675cd 53sub register_class {
54 my ($class, $name, $to_register) = @_;
74b92d9a 55 my %reg = %{$class->class_registrations};
a02675cd 56 $reg{$name} = $to_register;
74b92d9a 57 $class->class_registrations(\%reg);
58}
59
60sub registered_classes {
61 return values %{shift->class_registrations};
a02675cd 62}
63
64sub load_classes {
65 my $class = shift;
66 my @comp = grep { $_ !~ /^#/ } @_;
41a6f8c0 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 }
a02675cd 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
82sub compose_connection {
83 my ($class, $target, @info) = @_;
b7951443 84 $class->setup_connection_class($target, @info);
74b92d9a 85 my %reg = %{ $class->class_registrations };
a02675cd 86 while (my ($comp, $comp_class) = each %reg) {
87 my $target_class = "${target}::${comp}";
b7951443 88 $class->inject_base($target_class, $comp_class, $target);
89 }
90}
91
92sub 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
99sub inject_base {
100 my ($class, $target, @to_inject) = @_;
101 {
102 no strict 'refs';
103 unshift(@{"${target}::ISA"}, @to_inject);
a02675cd 104 }
105}
106
1071;
c2da098a 108
109=back
110
111=head1 AUTHORS
112
113Matt S. Trout <perl-stuff@trout.me.uk>
114
115=head1 LICENSE
116
117You may distribute this code under the same terms as Perl itself.
118
119=cut
120