checkpoint
[p5sagit/Class-C3-Componentised.git] / lib / Class / C3 / Componentised.pm
1 package Class::C3::Componentised;
2
3 use strict;
4 use warnings;
5
6 use vars qw($VERSION);
7
8 use Class::C3;
9
10 $VERSION = "0.01";
11
12 sub inject_base {
13   my ($class, $target, @to_inject) = @_;
14   {
15     no strict 'refs';
16     my %seen;
17     unshift( @{"${target}::ISA"},
18         grep { !$seen{ $_ }++ && $target ne $_ && !$target->isa($_) }
19             @to_inject
20     );
21   }
22
23   # Yes, this is hack. But it *does* work. Please don't submit tickets about
24   # it on the basis of the comments in Class::C3, the author was on #dbix-class
25   # while I was implementing this.
26
27   my $table = { Class::C3::_dump_MRO_table };
28   eval "package $target; import Class::C3;" unless exists $table->{$target};
29 }
30
31 sub load_components {
32   my $class = shift;
33   my $base = $class->component_base_class;
34   my @comp = map { /^\+(.*)$/ ? $1 : "${base}::$_" } grep { $_ !~ /^#/ } @_;
35   $class->_load_components(@comp);
36   Class::C3::reinitialize();
37 }
38
39 sub load_own_components {
40   my $class = shift;
41   my @comp = map { "${class}::$_" } grep { $_ !~ /^#/ } @_;
42   $class->_load_components(@comp);
43 }
44
45 sub _load_components {
46   my ($class, @comp) = @_;
47   foreach my $comp (@comp) {
48     eval "use $comp";
49     die $@ if $@;
50   }
51   $class->inject_base($class => @comp);
52 }
53
54 1;
55
56 __END__
57
58 =head1 NAME
59
60 Class::C3::Componentised - extend and mix classes at runtime
61
62 =head1 SYNOPSIS
63
64     package MyApp;
65
66     use base "Class::C3::Componentised";
67
68     sub component_base_class { "MyApp" };
69     
70
71     package main;
72
73     MyApp->load_components(qw/Foo Bar Baz/);
74
75 =head1 DESCRIPTION
76
77 =head2 inject_base
78
79 =head2 load_components
80
81 =head2 load_own_components
82
83 =head1 AUTHOR
84
85 Matt S. Trout <mst@shadowcatsystems.co.uk>
86
87 =head1 LICENSE
88
89 You may distribute this code under the same terms as Perl itself.