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