1Catalyst::Manual::ExtenUdsienrgCCaotnatlryisbtu(t3e)d PeCraltaDloycsutm:e:nMtaantuiaoln::ExtendingCatalyst(3)
2
3
4

NAME

6       Catalyst::Manual::ExtendingCatalyst - Extending The Framework
7

DESCRIPTION

9       This document will provide you with access points, techniques and best
10       practices to extend the Catalyst framework, or to find more elegant
11       ways to abstract and use your own code.
12
13       The design of Catalyst is such that the framework itself should not get
14       in your way. There are many entry points to alter or extend Catalyst's
15       behaviour, and this can be confusing. This document is written to help
16       you understand the possibilities, current practices and their
17       consequences.
18
19       Please read the "BEST PRACTICES" section before deciding on a design,
20       especially if you plan to release your code to CPAN. The Catalyst
21       developer and user communities, which you are part of, will benefit
22       most if we all work together and coordinate.
23
24       If you are unsure on an implementation or have an idea you would like
25       to have RFC'ed, it surely is a good idea to send your questions and
26       suggestions to the Catalyst mailing list (See "SUPPORT" in Catalyst)
27       and/or come to the "#catalyst" channel on the "irc.perl.org" network.
28       You might also want to refer to those places for research to see if a
29       module doing what you're trying to implement already exists. This might
30       give you a solution to your problem or a basis for starting.
31

BEST PRACTICES

33       During Catalyst's early days, it was common to write plugins to provide
34       functionality application wide. Since then, Catalyst has become a lot
35       more flexible and powerful. It soon became a best practice to use some
36       other form of abstraction or interface, to keep the scope of its
37       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 "Namespaces".
42
43   Quick Checklist
44       Use the "CatalystX::*" namespace if you can!
45           If your extension isn't a Model, View, Controller, Plugin, Engine,
46           or Log, it's best to leave it out of the "Catalyst::" namespace.
47           Use <CatalystX::> instead.
48
49       Don't make it a plugin unless you have to!
50           A plugin should be careful since it's overriding Catalyst
51           internals.  If your plugin doesn't really need to muck with the
52           internals, make it a base Controller or Model.
53
54           Also, if you think you really need a plugin, please instead
55           consider using a Moose::Role.
56
57       There's a community. Use it!
58           There are many experienced developers in the Catalyst community,
59           there's always the IRC channel and the mailing list to discuss
60           things.
61
62       Add tests and documentation!
63           This gives a stable basis for contribution, and even more
64           importantly, builds trust. The easiest way is a test application.
65           See Catalyst::Manual::Tutorial::Testing for more information.
66
67   Namespaces
68       While some core extensions (engines, plugins, etc.) have to be placed
69       in the "Catalyst::*" namespace, the Catalyst core would like to ask
70       developers to use the "CatalystX::*" namespace if possible.
71
72       Please do not invent components which are outside the well known
73       "Model", "View", "Controller" or "Plugin" namespaces!
74
75       When you try to put a base class for a "Model", "View" or "Controller"
76       directly under your "MyApp" directory as, for example,
77       "MyApp::Controller::Foo", you will have the problem that Catalyst will
78       try to load that base class as a component of your application. The
79       solution is simple: Use another namespace. Common ones are
80       "MyApp::Base::Controller::*" or "MyApp::ControllerBase::*" as examples.
81
82   Can it be a simple module?
83       Sometimes you want to use functionality in your application that
84       doesn't require the framework at all. Remember that Catalyst is just
85       Perl and you always can just "use" a module. If you have application
86       specific code that doesn't need the framework, there is no problem in
87       putting it in your "MyApp::*" namespace. Just don't put it in "Model",
88       "Controller" or "View", because that would make Catalyst try to load
89       them as components.
90
91       Writing a generic component that only works with Catalyst is wasteful
92       of your time.  Try writing a plain perl module, and then a small bit of
93       glue that integrates it with Catalyst.  See
94       Catalyst::Model::DBIC::Schema for a module that takes the approach.
95       The advantage here is that your "Catalyst" DBIC schema works perfectly
96       outside of Catalyst, making testing (and command-line scripts) a
97       breeze.  The actual Catalyst Model is just a few lines of glue that
98       makes working with the schema convenient.
99
100       If you want the thinnest interface possible, take a look at
101       Catalyst::Model::Adaptor.
102
103   Using Moose roles to apply method modifiers
104       Rather than having a complex set of base classes which you have to
105       mixin via multiple inheritance, if your functionality is well
106       structured, then it's possible to use the composability of Moose roles,
107       and method modifiers to hook onto to provide functionality.
108
109       These can be applied to your models/views/controllers, and your
110       application class, and shipped to CPAN.  Please see
111       Catalyst::Manual::CatalystAndMoose for specific information about using
112       Roles in combination with Catalyst, and Moose::Manual::Roles for more
113       information about roles in general.
114
115   Inheritance and overriding methods
116       When overriding a method, keep in mind that some day additional
117       arguments may be provided to the method, if the last parameter is not a
118       flat list. It is thus better to override a method by shifting the
119       invocant off of @_ and assign the rest of the used arguments, so you
120       can pass your complete arguments to the original method via @_:
121
122         use MRO::Compat; ...
123
124         sub foo {
125           my $self = shift;
126           my ($bar, $baz) = @_; # ...  return
127           $self->next::method(@_);
128         }
129
130       If you would do the common
131
132         my ($self, $foo, $bar) = @_;
133
134       you'd have to use a much uglier construct to ensure that all arguments
135       will be passed along and the method is future proof:
136
137         $self->next::method(@_[ 1 .. $#_ ]);
138
139   Tests and documentation
140       When you release your module to the CPAN, proper documentation and at
141       least a basic test suite (which means more than pod or even just
142       "use_ok", sorry) gives people a good base to contribute to the module.
143       It also shows that you care for your users. If you would like your
144       module to become a recommended addition, these things will prove
145       invaluable.
146
147       If you're just getting started, try using CatalystX::Starter to
148       generate some example tests for your module.
149
150   Maintenance
151       In planning to release a module to the community (Catalyst or CPAN and
152       Perl), you should consider if you have the resources to keep it up to
153       date, including fixing bugs and accepting contributions.
154
155       If you're not sure about this, you can always ask in the proper
156       Catalyst or Perl channels if someone else might be interested in the
157       project, and would jump in as co-maintainer.
158
159       A public repository can further ease interaction with the community.
160       Even read only access enables people to provide you with patches to
161       your current development version. subversion, SVN and SVK, are broadly
162       preferred in the Catalyst community.
163
164       If you're developing a Catalyst extension, please consider asking the
165       core team for space in Catalyst's own subversion repository. You can
166       get in touch about this via IRC or the Catalyst developers mailing
167       list.
168
169   The context object
170       Sometimes you want to get a hold of the context object in a component
171       that was created on startup time, where no context existed yet. Often
172       this is about the model reading something out of the stash or other
173       context information (current language, for example).
174
175       If you use the context object in your component you have tied it to an
176       existing request.  This means that you might get into problems when you
177       try to use the component (e.g. the model - the most common case)
178       outside of Catalyst, for example in cronjobs.
179
180       A stable solution to this problem is to design the Catalyst model
181       separately from the underlying model logic. Let's take
182       Catalyst::Model::DBIC::Schema as an example. You can create a schema
183       outside of Catalyst that knows nothing about the web. This kind of
184       design ensures encapsulation and makes development and maintenance a
185       whole lot easier. The you use the aforementioned model to tie your
186       schema to your application. This gives you a "MyApp::DBIC" (the name is
187       of course just an example) model as well as "MyApp::DBIC::TableName"
188       models to access your result sources directly.
189
190       By creating such a thin layer between the actual model and the Catalyst
191       application, the schema itself is not at all tied to any application
192       and the layer in-between can access the model's API using information
193       from the context object.
194
195       A Catalyst component accesses the context object at request time with
196       "ACCEPT_CONTEXT($c, @args)" in Catalyst::Component.
197

CONFIGURATION

199       The application has to interact with the extension with some
200       configuration. There is of course again more than one way to do it.
201
202   Attributes
203       You can specify any valid Perl attribute on Catalyst actions you like.
204       (See "Syntax of Attribute Lists" in attributes for a description of
205       what is valid.) These will be available on the Catalyst::Action
206       instance via its "attributes" accessor. To give an example, this
207       action:
208
209         sub foo : Local Bar('Baz') {
210             my ($self, $c) = @_;
211             my $attributes = $self->action_for('foo')->attributes;
212             $c->res->body($attributes->{Bar}[0] );
213         }
214
215       will set the response body to "Baz". The values always come in an array
216       reference. As you can see, you can use attributes to configure your
217       actions. You can specify or alter these attributes via "Component
218       Configuration", or even react on them as soon as Catalyst encounters
219       them by providing your own component base class.
220
221   Component Configuration
222       At creation time, the class configuration of your component (the one
223       available via "$self->config") will be merged with possible
224       configuration settings from the applications configuration (either
225       directly or via config file). This is done by Catalyst, and the
226       correctly merged configuration is passed to your component's
227       constructor (i.e. the new method).
228
229       Ergo, if you define an accessor for each configuration value that your
230       component takes, then the value will be automatically stored in the
231       controller object's hash reference, and available from the accessor.
232
233       The "config" accessor always only contains the original class
234       configuration and you MUST NEVER call "$self->config" to get your
235       component configuration, as the data there is likely to be a subset of
236       the correct config.
237
238       For example:
239
240         package MyApp
241         use Moose;
242
243         extends 'Catalyst';
244
245         ...
246
247         __PACKAGE__->config(
248           'Controller::Foo' => { some_value => 'bar' },
249         );
250
251         ...
252
253         package MyApp::Controller::Foo;
254         use Moose;
255         use namespace::autoclean;
256         BEGIN { extends 'Catalyst::Controller' };
257
258         has some_value ( is => 'ro', required => 1 );
259
260         sub some_method {
261             my $self = shift;
262             return "the value of 'some_value' is " . $self->some_value;
263         }
264
265         ...
266
267         my $controller = $c->controller('Foo');
268         warn $controller->some_value;
269         warn $controller->some_method;
270

IMPLEMENTATION

272       This part contains the technical details of various implementation
273       methods. Please read the "BEST PRACTICES" before you start your
274       implementation, if you haven't already.
275
276   Action classes
277       Usually, your action objects are of the class Catalyst::Action.  You
278       can override this with the "ActionClass" attribute to influence
279       execution and/or dispatching of the action. A widely used example of
280       this is Catalyst::Action::RenderView, which is used in every newly
281       created Catalyst application in your root controller:
282
283         sub end : ActionClass('RenderView') { }
284
285       Usually, you want to override the "execute" and/or the "match" method.
286       The execute method of the action will naturally call the methods code.
287       You can surround this by overriding the method in a subclass:
288
289         package Catalyst::Action::MyFoo;
290         use Moose;
291         use namespace::autoclean;
292         use MRO::Compat;
293         extends 'Catalyst::Action';
294
295         sub execute {
296             my $self = shift;
297             my ($controller, $c, @args) = @_;
298             # put your 'before' code here
299             my $r = $self->next::method(@_);
300             # put your 'after' code here
301             return $r;
302         }
303         1;
304
305       We are using MRO::Compat to ensure that you have the next::method call,
306       from Class::C3 (in older perls), or natively (if you are using perl
307       5.10) to re-dispatch to the original "execute" method in the
308       Catalyst::Action class.
309
310       The Catalyst dispatcher handles an incoming request and, depending upon
311       the dispatch type, will call the appropriate target or chain.  From
312       time to time it asks the actions themselves, or through the controller,
313       if they would match the current request. That's what the "match" method
314       does.  So by overriding this, you can change on what the action will
315       match and add new matching criteria.
316
317       For example, the action class below will make the action only match on
318       Mondays:
319
320         package Catalyst::Action::OnlyMondays;
321         use Moose;
322         use namespace::autoclean;
323         use MRO::Compat;
324         extends 'Catalyst::Action';
325
326         sub match {
327             my $self = shift;
328             return 0 if ( localtime(time) )[6] == 1;
329             return $self->next::method(@_);
330          }
331         1;
332
333       And this is how we'd use it:
334
335         sub foo: Local ActionClass('OnlyMondays') {
336             my ($self, $c) = @_;
337             $c->res->body('I feel motivated!');
338         }
339
340       If you are using action classes often or have some specific base
341       classes that you want to specify more conveniently, you can implement a
342       component base class providing an attribute handler.
343
344       It is not possible to use multiple action classes at once, however
345       Catalyst::Controller::ActionRole allows you to apply Moose Roles to
346       actions.
347
348       For further information on action classes and roles, please refer to
349       Catalyst::Action and Catalyst::Manual::Actions.
350
351   Component base classes
352       Many Catalyst::Plugin that were written in Catalyst's early days should
353       really have been just controller base classes. With such a class, you
354       could provide functionality scoped to a single controller, not
355       polluting the global namespace in the context object.
356
357       You can provide regular Perl methods in a base class as well as actions
358       which will be inherited to the subclass. Please refer to "Controllers"
359       for an example of this.
360
361       You can introduce your own attributes by specifying a handler method in
362       the controller base. For example, to use a "FullClass" attribute to
363       specify a fully qualified action class name, you could use the
364       following implementation. Note, however, that this functionality is
365       already provided via the "+" prefix for action classes. A simple
366
367         sub foo : Local ActionClass('+MyApp::Action::Bar') { ... }
368
369       will use "MyApp::Action::Bar" as action class.
370
371         package MyApp::Base::Controller::FullClass;
372         use Moose;
373         use namespace::autoclean;
374         BEGIN { extends '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 Catalyst
384       attribute:
385
386         package MyApp::Controller::Foo;
387         use Moose;
388         use namespace::autoclean;
389         BEGIN { extends 'MyApp::Base::Controller::FullClass'; }
390
391         sub foo : Local FullClass('MyApp::Action::Bar') { ... }
392
393         1;
394
395   Controllers
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 Moose;
406         use namespace::autoclean;
407
408         BEGIN { extends 'Catalyst::Controller'; }
409
410         sub list : Chained('base') PathPart('') Args(0) {
411             my ($self, $c) = @_;
412             my $model = $c->model( $self->{model_name} );
413             my $condition = $self->{model_search_condition} || {};
414             my $attrs = $self->{model_search_attrs} || {};
415             $c->stash(rs => $model->search($condition, $attrs);
416         }
417
418         sub load : Chained('base') PathPart('') CaptureArgs(1) {
419             my ($self, $c, $id) = @_;
420             my $model = $c->model( $self->{model_name} );
421             $c->stash(row => $model->find($id));
422         }
423         1;
424
425       This example implements two simple actions. The "list" action chains to
426       a (currently non-existent) "base" action and puts a result-set into the
427       stash taking a configured "model_name" as well as a search condition
428       and attributes. This action is a chained endpoint. The other action,
429       called " load " is a chain midpoint that takes one argument. It takes
430       the value as an ID and loads the row from the configured model. Please
431       not that the above code is simplified for clarity. It misses error
432       handling, input validation, and probably other things.
433
434       The class above is not very useful on its own, but we can combine it
435       with some custom actions by sub-classing it:
436
437         package MyApp::Controller::Foo;
438         use Moose;
439         use namespace::autoclean;
440
441         BEGIN { extends 'MyApp::Base::Controller::ModelBase'; }
442
443         __PACKAGE__->config( model_name => 'DB::Foo',
444                              model_search_condition=> { is_active => 1 },
445                              model_search_attrs => { order_by => 'name' },
446                          );
447
448         sub base : Chained PathPart('foo') CaptureArgs(0) { }
449
450         sub view : Chained('load') Args(0) {
451             my ($self, $c) = @_;
452             my $row = $c->stash->{row};
453             $c->res->body(join ': ', $row->name,
454             $row->description); }
455         1;
456
457       This class uses the formerly created controller as a base class. First,
458       we see the configurations that were used in the parent class. Next
459       comes the "base" action, where everything chains off of.
460
461       Note that inherited actions act like they were declared in your
462       controller itself. You can therefor call them just by their name in
463       "forward"s, "detaches" and "Chained(..)" specifications. This is an
464       important part of what makes this technique so useful.
465
466       The new "view" action ties itself to the "load" action specified in the
467       base class and outputs the loaded row's "name" and "description"
468       columns. The controller "MyApp::Controller::Foo" now has these publicly
469       available paths:
470
471       /foo
472           Will call the controller's "base", then the base classes "list"
473           action.
474
475       /foo/$id/view
476           First, the controller's "base" will be called, then it will "load"
477           the row with the corresponding $id. After that, "view" will display
478           some fields out of the object.
479
480   Models and Views
481       If the functionality you'd like to add is really a data-set that you
482       want to manipulate, for example internal document types, images, files,
483       it might be better suited as a model.
484
485       The same applies for views. If your code handles representation or
486       deals with the applications interface and should be universally
487       available, it could be a perfect candidate for a view.
488
489       Please implement a "process" method in your views. This method will be
490       called by Catalyst if it is asked to forward to a component without a
491       specified action. Note that "process" is not a Catalyst action but a
492       simple Perl method.
493
494       You are also encouraged to implement a "render" method corresponding
495       with the one in Catalyst::View::TT. This has proven invaluable, because
496       people can use your view for much more fine-grained content generation.
497
498       Here is some example code for a fictional view:
499
500         package Catalyst::View::MyView;
501         use Moose;
502         use namespace::autoclean;
503
504         extends 'Catalyst::View';
505
506         sub process {
507             my ($self, $c) = @_;
508             my $template = $c->stash->{template};
509             my $content = $self->render($c, $template, $c->stash);
510             $c->res->body( $content );
511         }
512
513         sub render {
514             my ($self, $c, $template, $args) = @_;
515             # prepare content here
516             return $content;
517         }
518         1;
519
520   Plugins
521       The first thing to say about plugins is that if you're not sure if your
522       module should be a plugin, it probably shouldn't. It once was common to
523       add features to Catalyst by writing plugins that provide accessors to
524       said functionality. As Catalyst grew more popular, it became obvious
525       that this qualifies as bad practice.
526
527       By designing your module as a Catalyst plugin, every method you
528       implement, import or inherit will be available via your applications
529       context object.  A plugin pollutes the global namespace, and you should
530       be only doing that when you really need to.
531
532       Often, developers design extensions as plugins because they need to get
533       hold of the context object. Either to get at the stash or
534       request/response objects are the widely spread reasons. It is, however,
535       perfectly possible to implement a regular Catalyst component (read:
536       model, view or controller) that receives the current context object via
537       "ACCEPT_CONTEXT($c, @args)" in Catalyst::Component.
538
539       When is a plugin suited to your task? Your code needs to be a plugin to
540       act upon or alter specific parts of Catalyst's request lifecycle. If
541       your functionality needs to change some "prepare_*" or "finalize_*"
542       stages, you won't get around a plugin.
543
544       Note, if you just want to hook into such a stage, and run code before,
545       or after it, then it is recommended that you use Moose's method
546       modifiers to do this.
547
548       Another valid target for a plugin architecture are things that really
549       have to be globally available, like sessions or authentication.
550
551       Please do not release Catalyst extensions as plugins only to provide
552       some functionality application wide. Design it as a controller base
553       class or another better suited technique with a smaller scope, so that
554       your code only influences those parts of the application where it is
555       needed, and namespace clashes and conflicts are ruled out.
556
557       The implementation is pretty easy. Your plugin will be inserted in the
558       application's inheritance list, above Catalyst itself. You can by this
559       alter Catalyst's request lifecycle behaviour. Every method you declare,
560       every import in your package will be available as method on the
561       application and the context object. As an example, let's say you want
562       Catalyst to warn you every time uri_for was called without an action
563       object as the first parameter, for example to test that all your
564       chained uris are generated from actions (a recommended best practice).
565       You could do this with this simple implementation (excuse the lame
566       class name, it's just an example):
567
568         package Catalyst::Plugin::UriforUndefWarning;
569         use strict;
570         use Scalar::Util qw/blessed/;
571         use MRO::Compat;
572
573         sub uri_for {
574             my $c = shift;
575             my $uri = $c->next::method(@_);
576             $c->log->warn( 'uri_for with non action: ', join(', ', @_), )
577               if (!blessed($_[0]) || !$_[0]->isa('Catalyst::Action'));
578             return $uri;
579         }
580
581         1;
582
583       This would override Catalyst's "uri_for" method and emit a "warn" log
584       entry containing the arguments to uri_for.
585
586       Please note this is not a practical example, as string URLs are fine
587       for static content etc.
588
589       A simple example like this is actually better as a Moose role, for
590       example:
591
592         package CatalystX::UriforUndefWarning;
593         use Moose::Role;
594         use namespace::autoclean;
595
596         after 'uri_for' => sub {
597           my ($c, $arg) = @_;
598           $c->log->warn( 'uri_for with non action: ', join(', ', @_), )
599             if (!blessed($_[0]) || !$_[0]->isa('Catalyst::Action'));
600           return $uri;
601         };
602
603       Note that Catalyst will load any Moose Roles in the plugin list, and
604       apply them to your application class.
605
606   Factory components with COMPONENT()
607       Every component inheriting from Catalyst::Component contains a
608       "COMPONENT" method. It is used on application startup by
609       "setup_components" to instantiate the component object for the Catalyst
610       application. By default, this will merge the components own
611       "config"uration with the application wide overrides and call the class'
612       "new" method to return the component object.
613
614       You can override this method and do and return whatever you want.
615       However, you should use Class::C3 (via MRO::Compat) to forward to the
616       original "COMPONENT" method to merge the configuration of your
617       component.
618
619       Here is a stub "COMPONENT" method:
620
621         package CatalystX::Component::Foo;
622         use Moose;
623         use namespace::autoclean;
624
625         extends 'Catalyst::Component';
626
627         sub COMPONENT {
628             my $class = shift;
629             # Note: $app is like $c, but since the application isn't fully
630             # initialized, we don't want to call it $c yet.  $config
631             # is a hashref of config options possibly set on this component.
632             my ($app, $config) = @_;
633
634             # Do things here before instantiation
635             $new = $class->next::method(@_);
636             # Do things to object after instantiation
637             return $new;
638         }
639
640       The arguments are the class name of the component, the class name of
641       the application instantiating the component, and a hash reference with
642       the controller's configuration.
643
644       You are free to re-bless the object, instantiate a whole other
645       component or really do anything compatible with Catalyst's expectations
646       on a component.
647
648       For more information, please see "COMPONENT($c,$arguments)" in
649       Catalyst::Component.
650
651   Applying roles to parts of the framework
652       CatalystX::RoleApplicator will allow you to apply Roles to the
653       following classes:
654
655       Request
656       Response
657       Engine
658       Dispatcher
659       Stats
660
661       These roles can add new methods to these classes, or wrap preexisting
662       methods.
663
664       The namespace for roles like this is "Catalyst::TraitFor::XXX::YYYY".
665
666       For an example of a CPAN component implemented in this manor, see
667       Catalyst::TraitFor::Request::BrowserDetect.
668

SEE ALSO

670       Catalyst, Catalyst::Manual::Actions, Catalyst::Component
671

AUTHORS

673       Catalyst Contributors, see Catalyst.pm
674
676       This library is free software. You can redistribute it and/or modify it
677       under the same terms as Perl itself.
678
679
680
681perl v5.36.0                      2022-07C-a2t2alyst::Manual::ExtendingCatalyst(3)
Impressum