1 package MooseX::Object::Pluggable;
8 use Module::Pluggable::Object;
10 our $VERSION = '0.0005';
14 MooseX::Object::Pluggable - Make your classes pluggable
21 with 'MooseX::Object::Pluggable';
25 package MyApp::Plugin::Pretty;
28 sub pretty{ print "I am pretty" }
35 $app->load_plugin('Pretty');
40 This module is meant to be loaded as a role from Moose-based classes
41 it will add five methods and four attributes to assist you with the loading
42 and handling of plugins and extensions for plugins. I understand that this may
43 pollute your namespace, however I took great care in using the least ambiguous
46 =head1 How plugins Work
48 Plugins and extensions are just Roles by a fancy name. They are loaded at runtime
49 on demand and are instance, not class based. This means that if you have more than
50 one instance of a class they can all have different plugins loaded. This is a feature.
52 Plugin methods are allowed to C<around>, C<before>, C<after>
53 their consuming classes, so it is important to watch for load order as plugins can
54 and will overload each other. You may also add attributes through has.
56 Please note that when you load at runtime you lose the ability to wrap C<BUILD>
57 and roles using C<has> will not go through comile time checks like C<required>
60 Even though C<override> will work , I STRONGLY discourage it's use
61 and a warning will be thrown if you try to use it.
62 This is closely linked to the way multiple roles being applies is handles and is not
63 likely to change. C<override> bevavior is closely linked to inheritance and thus will
64 likely not work as you expect it in multiple inheritance situations. Point being,
65 save yourself the headache.
67 =head1 How plugins are loaded
69 When roles are applied at runtime an anonymous class will wrap your class and
70 C<$self-E<gt>blessed> and C<ref $self> will no longer return the name of your object,
71 they will instead return the name of the anonymous class created at runtime.
72 See C<_original_class_name>.
76 For a simple example see the tests included in this distribution.
82 String. The prefix to use for plugin names provided. MyApp::Plugin is sensible.
86 Boolean. Indicates whether we should attempt to load plugin extensions.
91 String. The namespace plugin extensions have. Defaults to 'ExtensionFor'.
93 This means that is _plugin_ns is "MyApp::Plugin" and _plugin_ext_ns is
94 "ExtensionFor" loading plugin "Bar" would search for extensions in
95 "MyApp::Plugin::Bar::ExtensionFor::*".
99 ArrayRef, Accessor automatically dereferences into array on a read call.
100 By default will be filled with the class name and it's prescedents, it is used
101 to determine which directories to look for plugins as well as which plugins
102 take presedence upon namespace collitions. This allows you to subclass a pluggable
103 class and still use it's plugins while using yours first if they are available.
107 =head2 _plugin_locator
109 An automatically built instance of L<Module::Pluggable::Object> used to locate
114 #--------#---------#---------#---------#---------#---------#---------#---------#
116 has _plugin_ns => (is => 'rw', required => 1, isa => 'Str',
117 default => 'Plugin');
118 has _plugin_ext => (is => 'rw', required => 1, isa => 'Bool',
120 has _plugin_ext_ns => (is => 'rw', required => 1, isa => 'Str',
121 default => 'ExtensionFor');
122 has _plugin_loaded => (is => 'rw', required => 1, isa => 'HashRef',
123 default => sub{ {} });
124 has _plugin_app_ns => (is => 'rw', required => 1, isa => 'ArrayRef', lazy => 1,
126 default => sub{ shift->_build_plugin_app_ns });
127 has _plugin_locator => (is => 'rw', required => 1, lazy => 1,
128 isa => 'Module::Pluggable::Object',
129 default => sub{ shift->_build_plugin_locator });
131 #--------#---------#---------#---------#---------#---------#---------#---------#
133 =head1 Public Methods
135 =head2 load_plugin $plugin
137 This is the only method you should be using. Load the apropriate role for
138 C<$plugin> as well as any extensions it provides if extensions are enabled.
143 my ($self, $plugin) = @_;
144 die("You must provide a plugin name") unless $plugin;
146 my $loaded = $self->_plugin_loaded;
147 return 1 if exists $loaded->{$plugin};
149 my $role = $self->_role_from_plugin($plugin);
151 $loaded->{$plugin} = $role if $self->_load_and_apply_role($role);
152 $self->load_plugin_ext($plugin) if $self->_plugin_ext;
154 return exists $loaded->{$plugin};
158 =head2 load_plugin_ext
160 Will load any extensions for a particular plugin. This should be called
161 automatically by C<load_plugin> so you don't need to worry about it.
162 It basically attempts to load any extension that exists for a plugin
163 that is already loaded. The only reason for using this is if you want to
164 keep _plugin_ext as false and only load extensions manually, which I don't
170 my ($self, $plugin) = @_;
171 die("You must provide a plugin name") unless $plugin;
172 my $role = $self->_plugin_loaded->{$plugin};
174 # $p for plugin, $r for role
175 while( my($p,$r) = each %{ $self->_plugin_loaded }){
177 my $ext = join "::", $role, $self->_plugin_ext_ns, $p;
178 if( $plugin =~ /^\+(.*)/ ){
179 eval{ $self->_load_and_apply_role( $ext ) };
181 $self->_load_and_apply_role( $ext ) if
182 grep{ /^${ext}$/ } $self->_plugin_locator->plugins;
185 #go back to prev loaded modules and load extensions for current module?
186 #my $ext2 = join "::", $r, $self->_plugin_ext_ns, $plugin;
187 #$self->_load_and_apply_role( $ext2 )
188 # if Class::Inspector->installed($ext2);
192 =head2 _original_class_name
194 Because of the way roles apply C<$self-E<gt>blessed> and C<ref $self> will
195 no longer return what you expect. Instead use this class to get your original
200 sub _original_class_name{
202 return (grep {$_ !~ /^Moose::/} $self->meta->class_precedence_list)[0];
206 =head1 Private Methods
208 There's nothing stopping you from using these, but if you are using them
209 for anything thats not really complicated you are probably doing
210 something wrong. Some of these may be inlined in the future if performance
211 becomes an issue (which I doubt).
213 =head2 _role_from_plugin $plugin
215 Creates a role name from a plugin name. If the plugin name is prepended
216 with a C<+> it will be treated as a full name returned as is. Otherwise
217 a string consisting of C<$plugin> prepended with the C<_plugin_ns>
218 and the first valid value from C<_plugin_app_ns> will be returned. Example
220 #assuming appname MyApp and C<_plugin_ns> 'Plugin'
221 $self->_role_from_plugin("MyPlugin"); # MyApp::Plugin::MyPlugin
225 sub _role_from_plugin{
226 my ($self, $plugin) = @_;
228 return $1 if( $plugin =~ /^\+(.*)/ );
230 my $o = join '::', $self->_plugin_ns, $plugin;
231 #Father, please forgive me for I have sinned.
232 my @roles = grep{ /${o}$/ } $self->_plugin_locator->plugins;
234 die("Unable to locate plugin") unless @roles;
235 return $roles[0] if @roles == 1;
237 my @names = (grep {$_ !~ /^Moose::/} $self->meta->class_precedence_list);
239 my %presedence_list = map{ $i++; "${_}::${o}", $i } @names;
241 @roles = sort{ $presedence_list{$a} <=> $presedence_list{$b}} @roles;
246 =head2 _load_and_apply_role $role
248 Require C<$role> if it is not already loaded and apply it. This is
249 the meat of this module.
253 sub _load_and_apply_role{
254 my ($self, $role) = @_;
255 die("You must provide a role name") unless $role;
258 unless( Class::MOP::is_class_loaded($role) ){
259 eval Class::MOP::load_class($role) || die("Failed to load role: $role");
262 carp("Using 'override' is strongly discouraged and may not behave ".
263 "as you expect it to. Please use 'around'")
264 if scalar keys %{ $role->meta->get_override_method_modifiers_map };
266 #apply the plugin to the anon subclass
267 die("Failed to apply plugin: $role")
268 unless $role->meta->apply( $self );
273 =head2 _build_plugin_app_ns
275 Automatically builds the _plugin_app_ns attribute with the classes in the
276 class presedence list that are not part of Moose.
280 sub _build_plugin_app_ns{
282 my @names = (grep {$_ !~ /^Moose::/} $self->meta->class_precedence_list);
286 =head2 _build_plugin_locator
288 Automatically creates a L<Module::Pluggable::Object> instance with the correct
293 sub _build_plugin_locator{
296 my $locator = Module::Pluggable::Object->new
298 [ map { join '::', ($_, $self->_plugin_ns) } $self->_plugin_app_ns ]
305 Keep tests happy. See L<Moose>
315 L<Moose>, L<Moose::Role>, L<Class::Inspector>
319 Guillermo Roditi, <groditi@cpan.org>
325 Please report any bugs or feature requests to
326 C<bug-moosex-object-pluggable at rt.cpan.org>, or through the web interface at
327 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=MooseX-Object-Pluggable>.
328 I will be notified, and then you'll automatically be notified of progress on
329 your bug as I make changes.
333 You can find documentation for this module with the perldoc command.
335 perldoc MooseX-Object-Pluggable
337 You can also look for information at:
341 =item * AnnoCPAN: Annotated CPAN documentation
343 L<http://annocpan.org/dist/MooseX-Object-Pluggable>
347 L<http://cpanratings.perl.org/d/MooseX-Object-Pluggable>
349 =item * RT: CPAN's request tracker
351 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=MooseX-Object-Pluggable>
355 L<http://search.cpan.org/dist/MooseX-Object-Pluggable>
359 =head1 ACKNOWLEDGEMENTS
363 =item #Moose - Huge number of questions
365 =item Matt S Trout <mst@shadowcatsystems.co.uk> - ideas / planning.
367 =item Stevan Little - EVERYTHING. Without him this would have never happened.
373 Copyright 2007 Guillermo Roditi. All Rights Reserved. This is
374 free software; you may redistribute it and/or modify it under the same
375 terms as Perl itself.