Some notes and changed examples for using Moose in MyApp. There is more stuff to...
[catagits/Catalyst-Manual.git] / lib / Catalyst / Manual / ExtendingCatalyst.pod
1 =head1 NAME
2
3 Catalyst::Manual::ExtendingCatalyst - Extending The Framework
4
5 =head1 DESCRIPTION
6
7 This document will provide you with access points, techniques and best
8 practices to extend the L<Catalyst> framework, or to find more elegant
9 ways to abstract and use your own code.
10
11 The design of Catalyst is such that the framework itself should not
12 get in your way. There are many entry points to alter or extend
13 Catalyst's behaviour, and this can be confusing. This document is
14 written to help you understand the possibilities, current practices
15 and their consequences.
16
17 Please read the L<BEST PRACTICES> section before deciding on a design,
18 especially if you plan to release your code to CPAN. The Catalyst
19 developer and user communities, which B<you are part of>, will benefit
20 most if we all work together and coordinate.
21
22 If you are unsure on an implementation or have an idea you would like
23 to have RFC'ed, it surely is a good idea to send your questions and
24 suggestions to the Catalyst mailing list (See L<Catalyst/SUPPORT>)
25 and/or come to the C<#catalyst> channel on the C<irc.perl.org>
26 network. You might also want to refer to those places for research to
27 see if a module doing what you're trying to implement already
28 exists. This might give you a solution to your problem or a basis for
29 starting.
30
31 =head1 BEST PRACTICES
32
33 During Catalyst's early days, it was common to write plugins to
34 provide functionality application wide. Since then, Catalyst has
35 become a lot more flexible and powerful. It soon became a best
36 practice to use some other form of abstraction or interface, to keep
37 the scope of its influence as close as possible to where it belongs.
38
39 For those in a hurry, here's a quick checklist of some fundamental
40 points. If you are going to read the whole thing anyway, you can jump
41 forward to L</Namespaces>.
42
43 =head2 Quick Checklist
44
45 =over
46
47 =item Use the C<CatalystX::*> namespace if you can!
48
49 If your extension isn't a Model, View, Controller, Plugin, Engine,
50 or Log, it's best to leave it out of the C<Catalyst::> namespace.
51 Use <CatalystX::> instead.
52
53 =item Don't make it a plugin unless you have to!
54
55 A plugin should be careful since it's overriding Catalyst internals.
56 If your plugin doesn't really need to muck with the internals, make it a
57 base Controller or Model.
58
59 If you need to hook (but not alter) the internals, then make it a L<Moose::Role>
60
61 =item There's a community. Use it!
62
63 There are many experienced developers in the Catalyst community,
64 there's always the IRC channel and the mailing list to discuss things.
65
66 =item Add tests and documentation!
67
68 This gives a stable basis for contribution, and even more importantly,
69 builds trust. The easiest way is a test application. See
70 L<Catalyst::Manual::Tutorial::Testing> for more information.
71
72 =back
73
74 =head2 Namespaces
75
76 While some core extensions (engines, plugins, etc.) have to be placed
77 in the C<Catalyst::*> namespace, the Catalyst core would like to ask
78 developers to use the C<CatalystX::*> namespace if possible.
79
80 When you try to put a base class for a C<Model>, C<View> or
81 C<Controller> directly under your C<MyApp> directory as, for example,
82 C<MyApp::Controller::Foo>, you will have the problem that Catalyst
83 will try to load that base class as a component of your
84 application. The solution is simple: Use another namespace. Common
85 ones are C<MyApp::Base::Controller::*> or C<MyApp::ControllerBase::*>
86 as examples.
87
88 =head2 Can it be a simple module?
89
90 Sometimes you want to use functionality in your application that
91 doesn't require the framework at all. Remember that Catalyst is just
92 Perl and you always can just C<use> a module. If you have application
93 specific code that doesn't need the framework, there is no problem in
94 putting it in your C<MyApp::*> namespace. Just don't put it in
95 C<Model>, C<Controller> or C<View>, because that would make Catalyst
96 try to load them as components.
97
98 Writing a generic component that only works with Catalyst is wasteful
99 of your time.  Try writing a plain perl module, and then a small bit
100 of glue that integrates it with Catalyst.  See
101 L<Catalyst::Model::DBIC::Schema|Catalyst::Model::DBIC::Schema> for a
102 module that takes the approach.  The advantage here is that your
103 "Catalyst" DBIC schema works perfectly outside of Catalyst, making
104 testing (and command-line scripts) a breeze.  The actual Catalyst
105 Model is just a few lines of glue that makes working with the schema
106 convenient.
107
108 If you want the thinnest interface possible, take a look at
109 L<Catalyst::Model::Adaptor|Catalyst::Model::Adaptor>.
110
111 =head2 Using Moose roles to apply method modifiers
112
113 Rather than having a complex set of base classes which you have to mixin
114 via multiple inheritence, if your functionality is well structured, then
115 it's possible to use the composability of L<Moose> roles, and method modifiers
116 to hook onto to provide functionality. 
117
118 For a simple example of this, see L<CatalystX::REPL>.
119
120 B<Note:> Currently, controllers with attributes will not function correctly
121 in conjunction with Moose roles.
122
123 =head2 Inheritance and overriding methods
124
125 While Catalyst itself is still based on L<NEXT> (for multiple
126 inheritance), extension developers are encouraged to use L<Class::C3>,
127 via L<MRO::Compat>, which is what Catalyst will be switching to in the 
128 5.80 release.
129
130 When overriding a method, keep in mind that some day additionally
131 arguments may be provided to the method, if the last parameter is not
132 a flat list. It is thus better to override a method by shifting the
133 invocant off of C<@_> and assign the rest of the used arguments, so
134 you can pass your complete arguments to the original method via C<@_>:
135
136   use MRO::Compat; ...
137
138   sub foo { my $self = shift;
139             my ($bar, $baz) = @_; # ...  return
140             $self->next::method(@_); }
141
142 If you would do the common
143
144   my ($self, $foo, $bar) = @_;
145
146 you'd have to use a much uglier construct to ensure that all arguments
147 will be passed along and the method is future proof:
148
149   $self->next::method(@_[ 1 .. $#_ ]);
150
151 =head2 Tests and documentation
152
153 When you release your module to the CPAN, proper documentation and at
154 least a basic test suite (which means more than pod or even just
155 C<use_ok>, sorry) gives people a good base to contribute to the
156 module.  It also shows that you care for your users. If you would like
157 your module to become a recommended addition, these things will prove
158 invaluable.
159
160 If you're just getting started, try using
161 L<CatalystX::Starter|CatalystX::Starter> to generate some example
162 tests for your module.
163
164 =head2 Maintenance
165
166 In planning to release a module to the community (Catalyst or CPAN and
167 Perl), you should consider if you have the resources to keep it up to
168 date, including fixing bugs and accepting contributions.
169
170 If you're not sure about this, you can always ask in the proper
171 Catalyst or Perl channels if someone else might be interested in the
172 project, and would jump in as co-maintainer.
173
174 A public repository can further ease interaction with the
175 community. Even read only access enables people to provide you with
176 patches to your current development version. subversion, SVN and SVK,
177 are broadly preferred in the Catalyst community.
178
179 If you're developing a Catalyst extension, please consider asking the
180 core team for space in Catalyst's own subversion repository. You can
181 get in touch about this via IRC or the Catalyst developers mailing
182 list.
183
184 =head2 The context object
185
186 Sometimes you want to get a hold of the context object in a component
187 that was created on startup time, where no context existed yet. Often
188 this is about the model reading something out of the stash or other
189 context information (current language, for example).
190
191 If you use the context object in your component you have tied it to an
192 existing request.  This means that you might get into problems when
193 you try to use the component (e.g. the model - the most common case)
194 outside of Catalyst, for example in cronjobs.
195
196 A stable solution to this problem is to design the Catalyst model
197 separately from the underlying model logic. Let's take
198 L<Catalyst::Model::DBIC::Schema> as an example. You can create a
199 schema outside of Catalyst that knows nothing about the web. This kind
200 of design ensures encapsulation and makes development and maintenance
201 a whole lot easier. The you use the aforementioned model to tie your
202 schema to your application. This gives you a C<MyApp::DBIC> (the name
203 is of course just an example) model as well as
204 C<MyApp::DBIC::TableName> models to access your result sources
205 directly.
206
207 By creating such a thin layer between the actual model and the
208 Catalyst application, the schema itself is not at all tied to any
209 application and the layer in-between can access the model's API using
210 information from the context object.
211
212 A Catalyst component accesses the context object at request time with
213 L<Catalyst::Component/"ACCEPT_CONTEXT($c, @args)">.
214
215 =head1 CONFIGURATION
216
217 The application has to interact with the extension with some
218 configuration. There is of course again more than one way to do it.
219
220 =head2 Attributes
221
222 You can specify any valid Perl attribute on Catalyst actions you like.
223 (See L<attributes/"Syntax of Attribute Lists"> for a description of
224 what is valid.) These will be available on the C<Catalyst::Action>
225 instance via its C<attributes> accessor. To give an example, this
226 action:
227
228   sub foo : Local Bar('Baz') {
229       my ($self, $c) = @_;
230       my $attributes =
231       $self->action_for('foo')->attributes;
232       $c->res->body($attributes->{Bar}[0] );
233   }
234
235 will set the response body to C<Baz>. The values always come in an
236 array reference. As you can see, you can use attributes to configure
237 your actions. You can specify or alter these attributes via
238 L</"Component Configuration">, or even react on them as soon as
239 Catalyst encounters them by providing your own L<component base
240 class|/"Component Base Classes">.
241
242 =head2 Creating custom accessors
243
244 L<Catalyst::Component> uses L<Class::Accessor::Fast> for accessor
245 creation. Please refer to the modules documentation for usage
246 information.
247
248 =head2 Component configuration
249
250 At creation time, the class configuration of your component (the one
251 available via C<$self-E<gt>config>) will be merged with possible
252 configuration settings from the applications configuration (either
253 directly or via config file).  This is then stored in the controller
254 object's hash reference. So, if you read possible configurations like:
255
256   my $model_name = $controller->{model_name};
257
258 you will get the right value. The C<config> accessor always only
259 contains the original class configuration and must not be used for
260 component configuration.
261
262 You are advised to create accessors on your component class for your
263 configuration values. This is good practice and makes it easier to
264 capture configuration key typos. You can do this with the
265 C<mk_ro_accessors> method provided to L<Catalyst::Component> via
266 L<Class::Accessor::Fast>:
267
268   use base 'Catalyst::Controller';
269   __PACKAGE__->mk_ro_accessors('model_name');
270   ...
271   my $model_name = $controller->model_name;
272
273 =head1 IMPLEMENTATION
274
275 This part contains the technical details of various implementation
276 methods. Please read the L</"BEST PRACTICES"> before you start your
277 implementation, if you haven't already.
278
279 =head2 Action classes
280
281 Usually, your action objects are of the class L<Catalyst::Action>.
282 You can override this with the C<ActionClass> attribute to influence
283 execution and/or dispatching of the action. A widely used example of
284 this is L<Catalyst::Action::RenderView>, which is used in every newly
285 created Catalyst application in your root controller:
286
287   sub end : ActionClass('RenderView') { }
288
289 Usually, you want to override the C<execute> and/or the C<match>
290 method. The execute method of the action will naturally call the
291 methods code. You can surround this by overriding the method in a
292 subclass:
293
294   package Catalyst::Action::MyFoo; 
295   use strict;
296
297   use MRO::Compat; 
298   use base 'Catalyst::Action';
299
300   sub execute {
301       my $self = shift;
302       my ($controller, $c, @args) = @_;
303       # put your 'before' code here
304       my $r = $self->next::method(@_);
305       # put your 'after' code here
306       return $r;
307   }
308   1;
309
310 We are using L<MRO::Compat> to ensure that you have the next::method
311 call, from L<Class::C3> (in older perls), or natively (if you are using 
312 perl 5.10) to re-dispatch to the original C<execute> method in the 
313 L<Catalyst::Action> class.
314
315 The Catalyst dispatcher handles an incoming request and, depending
316 upon the dispatch type, will call the appropriate target or chain. 
317 From time to time it asks the actions themselves, or through the
318 controller, if they would match the current request. That's what the
319 C<match> method does.  So by overriding this, you can change on what
320 the action will match and add new matching criteria.
321
322 For example, the action class below will make the action only match on
323 Mondays:
324
325   package Catalyst::Action::OnlyMondays; 
326   use strict;
327
328   use MRO::Compat;
329   use base 'Catalyst::Action';
330
331   sub match {
332       my $self = shift;
333       return 0 if ( localtime(time) )[6] == 1;
334       return $self->next::method(@_);
335    }
336   1;
337
338 And this is how we'd use it:
339
340   sub foo: Local ActionClass('OnlyMondays') {
341       my ($self, $c) = @_;
342       $c->res->body('I feel motivated!');
343   }
344
345 If you are using action classes often or have some specific base
346 classes that you want to specify more conveniently, you can implement
347 a component base class providing an attribute handler.
348
349 For further information on action classes, please refer to
350 L<Catalyst::Action> and L<Catalyst::Manual::Actions>.
351
352 =head2 Component base classes
353
354 Many L<Catalyst::Plugin> that were written in Catalyst's early days
355 should really have been just controller base classes. With such a
356 class, you could provide functionality scoped to a single controller,
357 not polluting the global namespace in the context object.
358
359 You can provide regular Perl methods in a base class as well as
360 actions which will be inherited to the subclass. Please refer to
361 L</Controllers> for an example of this.
362
363 You can introduce your own attributes by specifying a handler method
364 in the controller base. For example, to use a C<FullClass> attribute
365 to specify a fully qualified action class name, you could use the
366 following implementation. Note, however, that this functionality is
367 already provided via the C<+> prefix for action classes. A simple
368
369   sub foo : Local ActionClass('+MyApp::Action::Bar') { ... }
370
371 will use C<MyApp::Action::Bar> as action class.
372
373   package MyApp::Base::Controller::FullClass; use strict; use base
374   'Catalyst::Controller';
375
376   sub _parse_FullClass_attr {
377       my ($self, $app_class, $action_name, $value, $attrs) = @_;
378       return( ActionClass => $value );
379   }
380   1;
381
382 Note that the full line of arguments is only provided for completeness
383 sake. We could use this attribute in a subclass like any other
384 Catalyst attribute:
385
386   package MyApp::Controller::Foo;
387   use strict;
388   use base 'MyApp::Base::Controller::FullClass';
389
390   sub foo : Local FullClass('MyApp::Action::Bar') { ... }
391
392   1;
393
394 =head2 Controllers
395
396 Many things can happen in controllers, and it often improves
397 maintainability to abstract some of the code out into reusable base
398 classes.
399
400 You can provide usual Perl methods that will be available via your
401 controller object, or you can even define Catalyst actions which will
402 be inherited by the subclasses. Consider this controller base class:
403
404   package MyApp::Base::Controller::ModelBase;
405   use strict;
406   use base 'Catalyst::Controller';
407
408   sub list : Chained('base') PathPart('') Args(0) {
409       my ($self, $c) = @_;
410       my $model = $c->model( $self->{model_name} );
411       my $condition = $self->{model_search_condition} || {};
412       my $attrs = $self->{model_search_attrs} || {};
413       $c->stash(rs => $model->search($condition, $attrs);
414       }
415
416   sub load : Chained('base') PathPart('') CaptureArgs(1) {
417       my ($self, $c, $id) = @_;
418       my $model = $c->model( $self->{model_name} );
419       $c->stash(row => $model->find($id));
420       }
421   1;
422
423 This example implements two simple actions. The C<list> action chains
424 to a (currently non-existent) C<base> action and puts a result-set
425 into the stash taking a configured C<model_name> as well as a search
426 condition and attributes. This action is a
427 L<chained|Catalyst::DispatchType::Chained> endpoint. The other action,
428 called C< load > is a chain midpoint that takes one argument. It takes
429 the value as an ID and loads the row from the configured model. Please
430 not that the above code is simplified for clarity. It misses error
431 handling, input validation, and probably other things.
432
433 The class above is not very useful on its own, but we can combine it
434 with some custom actions by sub-classing it:
435
436   package MyApp::Controller::Foo;
437   use strict;
438   use base 'MyApp::Base::Controller::ModelBase';
439
440   __PACKAGE__->config( model_name => 'DB::Foo',
441                        model_search_condition=> { is_active => 1 },
442                        model_search_attrs => { order_by => 'name' },
443                    );
444
445   sub base : Chained PathPart('foo') CaptureArgs(0) { }
446
447   sub view : Chained('load') Args(0) {
448       my ($self, $c) = @_;
449       my $row = $c->stash->{row};
450       $c->res->body(join ': ', $row->name,
451       $row->description); }
452   1;
453
454 This class uses the formerly created controller as a base
455 class. First, we see the configurations that were used in the parent
456 class. Next comes the C<base> action, where everything chains off of.
457
458 Note that inherited actions act like they were declared in your
459 controller itself. You can therefor call them just by their name in
460 C<forward>s, C<detaches> and C<Chained(..)> specifications. This is an
461 important part of what makes this technique so useful.
462
463 The new C<view> action ties itself to the C<load> action specified in
464 the base class and outputs the loaded row's C<name> and C<description>
465 columns. The controller C<MyApp::Controller::Foo> now has these
466 publicly available paths:
467
468 =over
469
470 =item /foo
471
472 Will call the controller's C<base>, then the base classes C<list>
473 action.
474
475 =item /foo/$id/view
476
477 First, the controller's C<base> will be called, then it will C<load>
478 the row with the corresponding C<$id>. After that, C<view> will
479 display some fields out of the object.
480
481 =back
482
483 =head2 Models and Views
484
485 If the functionality you'd like to add is really a data-set that you
486 want to manipulate, for example internal document types, images,
487 files, it might be better suited as a model.
488
489 The same applies for views. If your code handles representation or
490 deals with the applications interface and should be universally
491 available, it could be a perfect candidate for a view.
492
493 Please implement a C<process> method in your views. This method will
494 be called by Catalyst if it is asked to forward to a component without
495 a specified action. Note that C<process> is B<not a Catalyst action>
496 but a simple Perl method.
497
498 You are also encouraged to implement a C<render> method corresponding
499 with the one in L<Catalyst::View::TT>. This has proven invaluable,
500 because people can use your view for much more fine-grained content
501 generation.
502
503 Here is some example code for a fictional view:
504
505   package CatalystX::View::MyView;
506   use strict;
507   use base 'Catalyst::View';
508
509   sub process {
510       my ($self, $c) = @_;
511       my $template = $c->stash->{template};
512       my $content = $self->render($c, $template, $c->stash);
513       $c->res->body( $content );
514   }
515
516   sub render {
517       my ($self, $c, $template, $args) = @_;
518       # prepare content here
519       return $content;
520   }
521   1;
522
523 =head2 Plugins
524
525 The first thing to say about plugins is that if you're not sure if
526 your module should be a plugin, it probably shouldn't. It once was
527 common to add features to Catalyst by writing plugins that provide
528 accessors to said functionality. As Catalyst grew more popular, it
529 became obvious that this qualifies as bad practice.
530
531 By designing your module as a Catalyst plugin, every method you
532 implement, import or inherit will be available via your applications
533 context object.  A plugin pollutes the global namespace, and you
534 should be only doing that when you really need to.
535
536 Often, developers design extensions as plugins because they need to
537 get hold of the context object. Either to get at the stash or
538 request/response objects are the widely spread reasons. It is,
539 however, perfectly possible to implement a regular Catalyst component
540 (read: model, view or controller) that receives the current context
541 object via L<Catalyst::Component/"ACCEPT_CONTEXT($c, @args)">.
542
543 When is a plugin suited to your task? Your code needs to be a
544 plugin to act upon or alter specific parts of Catalyst's request
545 lifecycle. If your functionality needs to change some C<prepare_*> or
546 C<finalize_*> stages, you won't get around a plugin.
547
548 Note, if you just want to hook into such a stage, and run code before,
549 or after it, then it is recommended that you use L<Moose>s method modifiers
550 to do this.
551
552 Another valid target for a plugin architecture are things that
553 B<really> have to be globally available, like sessions or
554 authentication.
555
556 B<Please do not> release Catalyst extensions as plugins only to
557 provide some functionality application wide. Design it as a controller
558 base class or another suiting technique with a smaller scope, so that
559 your code only influences those parts of the application where it is
560 needed, and namespace clashes and conflicts are ruled out.
561
562 The implementation is pretty easy. Your plugin will be inserted in the
563 application's inheritance list, above Catalyst itself. You can by this
564 alter Catalyst's request lifecycle behaviour. Every method you
565 declare, every import in your package will be available as method on
566 the application and the context object. As an example, let's say you
567 want Catalyst to warn you every time uri_for was called without an action
568 object as the first parameter, for example to test that all your chained
569 uris are generated from actions (a recommended best practice).
570 You could do this with this simple
571 implementation (excuse the lame class name, it's just an example):
572
573   package Catalyst::Plugin::UriforUndefWarning;
574   use strict;
575   use Scalar::Util qw/blessed/;
576   use MRO::Compat;
577
578   sub uri_for {
579       my $c = shift;
580       my $uri = $c->next::method(@_);
581       $c->log->warn( 'uri_for with non action: ', join(', ', @_), )
582         if (!blessed($_[0]) || !$_[0]->isa('Catalyst::Action'));
583       return $uri;
584   }
585
586   1;
587
588 This would override Catalyst's C<uri_for> method and emit a C<warn>
589 log entry containing the arguments to uri_for.
590
591 Please note this is not a practical example, as string URLs are fine for
592 static content etc.
593
594 A simple example like this is actually better as a L<Moose> role, for example:
595
596   package CatalystX::UriforUndefWarning;
597   use Moose::Role;
598   use namespace::clean -except => 'meta';
599
600   after 'uri_for' => sub {
601     my ($c, $arg) = @_;
602     $c->log->warn( 'uri_for with non action: ', join(', ', @_), )
603       if (!blessed($_[0]) || !$_[0]->isa('Catalyst::Action'));
604     return $uri;
605   }; 
606
607 =head2 Factory components with COMPONENT()
608
609 Every component inheriting from L<Catalyst::Component> contains a
610 C<COMPONENT> method. It is used on application startup by
611 C<setup_components> to instantiate the component object for the
612 Catalyst application. By default, this will merge the components own
613 C<config>uration with the application wide overrides and call the
614 class' C<new> method to return the component object.
615
616 You can override this method and do and return whatever you want.
617 However, you should use L<Class::C3> (via L<MRO::Compat>) to forward 
618 to the original C<COMPONENT> method to merge the configuration of 
619 your component.
620
621 Here is a stub C<COMPONENT> method:
622
623   package CatalystX::Component::Foo;
624   use strict;
625   use base 'Catalyst::Component';
626
627   use MRO::Compat;
628
629   sub COMPONENT {
630       my $class = shift;
631       my ($app_class, $config) = @_;
632
633       # do things here before instantiation my
634       $obj = $self->next::method(@_);
635       # do things to object after instantiation
636       return $object;
637   }
638
639 The arguments are the class name of the component, the class name of
640 the application instantiating the component, and a hash reference with
641 the controller's configuration.
642
643 You are free to re-bless the object, instantiate a whole other
644 component or really do anything compatible with Catalyst's
645 expectations on a component.
646
647 For more information, please see L<Catalyst::Component/"COMPONENT($c,$arguments)">.
648
649 =head1 SEE ALSO
650
651 L<Catalyst>, L<Catalyst::Manual::Actions>, L<Catalyst::Component>
652
653 =head1 AUTHOR
654
655 Robert Sedlacek C<< <rs@474.at> >>
656
657 Jonathan Rockway C<< <jrockway@cpan.org> >>
658
659 =head1 LICENSE AND COPYRIGHT
660
661 This document is free, you can redistribute it and/or modify it under
662 the same terms as Perl itself.
663
664 =cut
665