1Catalyst(3) User Contributed Perl Documentation Catalyst(3)
2
3
4
6 Catalyst - The Elegant MVC Web Application Framework
7
9 See the Catalyst::Manual distribution for comprehensive documentation
10 and tutorials.
11
12 # Install Catalyst::Devel for helpers and other development tools
13 # use the helper to create a new application
14 catalyst.pl MyApp
15
16 # add models, views, controllers
17 script/myapp_create.pl model MyDatabase DBIC::Schema create=dynamic dbi:SQLite:/path/to/db
18 script/myapp_create.pl view MyTemplate TT
19 script/myapp_create.pl controller Search
20
21 # built in testserver -- use -r to restart automatically on changes
22 # --help to see all available options
23 script/myapp_server.pl
24
25 # command line testing interface
26 script/myapp_test.pl /yada
27
28 ### in lib/MyApp.pm
29 use Catalyst qw/-Debug/; # include plugins here as well
30
31 ### In lib/MyApp/Controller/Root.pm (autocreated)
32 sub foo : Global { # called for /foo, /foo/1, /foo/1/2, etc.
33 my ( $self, $c, @args ) = @_; # args are qw/1 2/ for /foo/1/2
34 $c->stash->{template} = 'foo.tt'; # set the template
35 # lookup something from db -- stash vars are passed to TT
36 $c->stash->{data} =
37 $c->model('Database::Foo')->search( { country => $args[0] } );
38 if ( $c->req->params->{bar} ) { # access GET or POST parameters
39 $c->forward( 'bar' ); # process another action
40 # do something else after forward returns
41 }
42 }
43
44 # The foo.tt TT template can use the stash data from the database
45 [% WHILE (item = data.next) %]
46 [% item.foo %]
47 [% END %]
48
49 # called for /bar/of/soap, /bar/of/soap/10, etc.
50 sub bar : Path('/bar/of/soap') { ... }
51
52 # called for all actions, from the top-most controller downwards
53 sub auto : Private {
54 my ( $self, $c ) = @_;
55 if ( !$c->user_exists ) { # Catalyst::Plugin::Authentication
56 $c->res->redirect( '/login' ); # require login
57 return 0; # abort request and go immediately to end()
58 }
59 return 1; # success; carry on to next action
60 }
61
62 # called after all actions are finished
63 sub end : Private {
64 my ( $self, $c ) = @_;
65 if ( scalar @{ $c->error } ) { ... } # handle errors
66 return if $c->res->body; # already have a response
67 $c->forward( 'MyApp::View::TT' ); # render template
68 }
69
70 ### in MyApp/Controller/Foo.pm
71 # called for /foo/bar
72 sub bar : Local { ... }
73
74 # called for /blargle
75 sub blargle : Global { ... }
76
77 # an index action matches /foo, but not /foo/1, etc.
78 sub index : Private { ... }
79
80 ### in MyApp/Controller/Foo/Bar.pm
81 # called for /foo/bar/baz
82 sub baz : Local { ... }
83
84 # first Root auto is called, then Foo auto, then this
85 sub auto : Private { ... }
86
87 # powerful regular expression paths are also possible
88 sub details : Regex('^product/(\w+)/details$') {
89 my ( $self, $c ) = @_;
90 # extract the (\w+) from the URI
91 my $product = $c->req->captures->[0];
92 }
93
94 See Catalyst::Manual::Intro for additional information.
95
97 Catalyst is a modern framework for making web applications without the
98 pain usually associated with this process. This document is a reference
99 to the main Catalyst application. If you are a new user, we suggest you
100 start with Catalyst::Manual::Tutorial or Catalyst::Manual::Intro.
101
102 See Catalyst::Manual for more documentation.
103
104 Catalyst plugins can be loaded by naming them as arguments to the "use
105 Catalyst" statement. Omit the "Catalyst::Plugin::" prefix from the
106 plugin name, i.e., "Catalyst::Plugin::My::Module" becomes "My::Module".
107
108 use Catalyst qw/My::Module/;
109
110 If your plugin starts with a name other than "Catalyst::Plugin::", you
111 can fully qualify the name by using a unary plus:
112
113 use Catalyst qw/
114 My::Module
115 +Fully::Qualified::Plugin::Name
116 /;
117
118 Special flags like "-Debug" and "-Engine" can also be specified as
119 arguments when Catalyst is loaded:
120
121 use Catalyst qw/-Debug My::Module/;
122
123 The position of plugins and flags in the chain is important, because
124 they are loaded in the order in which they appear.
125
126 The following flags are supported:
127
128 -Debug
129
130 Enables debug output. You can also force this setting from the system
131 environment with CATALYST_DEBUG or <MYAPP>_DEBUG. The environment set‐
132 tings override the application, with <MYAPP>_DEBUG having the highest
133 priority.
134
135 -Engine
136
137 Forces Catalyst to use a specific engine. Omit the "Catalyst::Engine::"
138 prefix of the engine name, i.e.:
139
140 use Catalyst qw/-Engine=CGI/;
141
142 -Home
143
144 Forces Catalyst to use a specific home directory, e.g.:
145
146 use Catalyst qw[-Home=/usr/mst];
147
148 This can also be done in the shell environment by setting either the
149 "CATALYST_HOME" environment variable or "MYAPP_HOME"; where "MYAPP" is
150 replaced with the uppercased name of your application, any "::" in the
151 name will be replaced with underscores, e.g. MyApp::Web should use
152 MYAPP_WEB_HOME. If both variables are set, the MYAPP_HOME one will be
153 used.
154
155 -Log
156
157 Specifies log level.
158
159 -Stats
160
161 Enables statistics collection and reporting. You can also force this
162 setting from the system environment with CATALYST_STATS or
163 <MYAPP>_STATS. The environment settings override the application, with
164 <MYAPP>_STATS having the highest priority.
165
166 e.g.
167
168 use Catalyst qw/-Stats=1/
169
171 INFORMATION ABOUT THE CURRENT REQUEST
172
173 $c->action
174
175 Returns a Catalyst::Action object for the current action, which
176 stringifies to the action name. See Catalyst::Action.
177
178 $c->namespace
179
180 Returns the namespace of the current action, i.e., the URI prefix cor‐
181 responding to the controller of the current action. For example:
182
183 # in Controller::Foo::Bar
184 $c->namespace; # returns 'foo/bar';
185
186 $c->request
187
188 $c->req
189
190 Returns the current Catalyst::Request object, giving access to informa‐
191 tion about the current client request (including parameters, cookies,
192 HTTP headers, etc.). See Catalyst::Request.
193
194 REQUEST FLOW HANDLING
195
196 $c->forward( $action [, \@arguments ] )
197
198 $c->forward( $class, $method, [, \@arguments ] )
199
200 Forwards processing to another action, by its private name. If you give
201 a class name but no method, "process()" is called. You may also option‐
202 ally pass arguments in an arrayref. The action will receive the argu‐
203 ments in @_ and "$c->req->args". Upon returning from the function,
204 "$c->req->args" will be restored to the previous values.
205
206 Any data "return"ed from the action forwarded to, will be returned by
207 the call to forward.
208
209 my $foodata = $c->forward('/foo');
210 $c->forward('index');
211 $c->forward(qw/MyApp::Model::DBIC::Foo do_stuff/);
212 $c->forward('MyApp::View::TT');
213
214 Note that forward implies an "<eval { }"> around the call (actually
215 "execute" does), thus de-fatalizing all 'dies' within the called
216 action. If you want "die" to propagate you need to do something like:
217
218 $c->forward('foo');
219 die $c->error if $c->error;
220
221 Or make sure to always return true values from your actions and write
222 your code like this:
223
224 $c->forward('foo') ⎪⎪ return;
225
226 $c->detach( $action [, \@arguments ] )
227
228 $c->detach( $class, $method, [, \@arguments ] )
229
230 $c->detach()
231
232 The same as "forward", but doesn't return to the previous action when
233 processing is finished.
234
235 When called with no arguments it escapes the processing chain entirely.
236
237 $c->response
238
239 $c->res
240
241 Returns the current Catalyst::Response object, see there for details.
242
243 $c->stash
244
245 Returns a hashref to the stash, which may be used to store data and
246 pass it between components during a request. You can also set hash keys
247 by passing arguments. The stash is automatically sent to the view. The
248 stash is cleared at the end of a request; it cannot be used for persis‐
249 tent storage (for this you must use a session; see Catalyst::Plug‐
250 in::Session for a complete system integrated with Catalyst).
251
252 $c->stash->{foo} = $bar;
253 $c->stash( { moose => 'majestic', qux => 0 } );
254 $c->stash( bar => 1, gorch => 2 ); # equivalent to passing a hashref
255
256 # stash is automatically passed to the view for use in a template
257 $c->forward( 'MyApp::View::TT' );
258
259 $c->error
260
261 $c->error($error, ...)
262
263 $c->error($arrayref)
264
265 Returns an arrayref containing error messages. If Catalyst encounters
266 an error while processing a request, it stores the error in $c->error.
267 This method should only be used to store fatal error messages.
268
269 my @error = @{ $c->error };
270
271 Add a new error.
272
273 $c->error('Something bad happened');
274
275 $c->state
276
277 Contains the return value of the last executed action.
278
279 $c->clear_errors
280
281 Clear errors. You probably don't want to clear the errors unless you
282 are implementing a custom error screen.
283
284 This is equivalent to running
285
286 $c->error(0);
287
288 COMPONENT ACCESSORS
289
290 $c->controller($name)
291
292 Gets a Catalyst::Controller instance by name.
293
294 $c->controller('Foo')->do_stuff;
295
296 If the name is omitted, will return the controller for the dispatched
297 action.
298
299 $c->model($name)
300
301 Gets a Catalyst::Model instance by name.
302
303 $c->model('Foo')->do_stuff;
304
305 Any extra arguments are directly passed to ACCEPT_CONTEXT.
306
307 If the name is omitted, it will look for
308 - a model object in $c->stash{current_model_instance}, then
309 - a model name in $c->stash->{current_model}, then
310 - a config setting 'default_model', or
311 - check if there is only one model, and return it if that's the case.
312
313 $c->controllers
314
315 Returns the available names which can be passed to $c->controller
316
317 $c->view($name)
318
319 Gets a Catalyst::View instance by name.
320
321 $c->view('Foo')->do_stuff;
322
323 Any extra arguments are directly passed to ACCEPT_CONTEXT.
324
325 If the name is omitted, it will look for
326 - a view object in $c->stash{current_view_instance}, then
327 - a view name in $c->stash->{current_view}, then
328 - a config setting 'default_view', or
329 - check if there is only one view, and return it if that's the case.
330
331 $c->models
332
333 Returns the available names which can be passed to $c->model
334
335 $c->views
336
337 Returns the available names which can be passed to $c->view
338
339 $c->comp($name)
340
341 $c->component($name)
342
343 Gets a component object by name. This method is not recommended, unless
344 you want to get a specific component by full class. "$c->controller",
345 "$c->model", and "$c->view" should be used instead.
346
347 CLASS DATA AND HELPER CLASSES
348
349 $c->config
350
351 Returns or takes a hashref containing the application's configuration.
352
353 __PACKAGE__->config( { db => 'dsn:SQLite:foo.db' } );
354
355 You can also use a "YAML", "XML" or "Config::General" config file like
356 myapp.yml in your applications home directory. See Catalyst::Plug‐
357 in::ConfigLoader.
358
359 ---
360 db: dsn:SQLite:foo.db
361
362 $c->log
363
364 Returns the logging object instance. Unless it is already set, Catalyst
365 sets this up with a Catalyst::Log object. To use your own log class,
366 set the logger with the "__PACKAGE__->log" method prior to calling
367 "__PACKAGE__->setup".
368
369 __PACKAGE__->log( MyLogger->new );
370 __PACKAGE__->setup;
371
372 And later:
373
374 $c->log->info( 'Now logging with my own logger!' );
375
376 Your log class should implement the methods described in Catalyst::Log.
377
378 $c->debug
379
380 Overload to enable debug messages (same as -Debug option).
381
382 Note that this is a static method, not an accessor and should be over‐
383 loaded by declaring "sub debug { 1 }" in your MyApp.pm, not by calling
384 $c->debug(1).
385
386 $c->dispatcher
387
388 Returns the dispatcher instance. Stringifies to class name. See Cata‐
389 lyst::Dispatcher.
390
391 $c->engine
392
393 Returns the engine instance. Stringifies to the class name. See Cata‐
394 lyst::Engine.
395
396 UTILITY METHODS
397
398 $c->path_to(@path)
399
400 Merges @path with "$c->config->{home}" and returns a Path::Class::Dir
401 object.
402
403 For example:
404
405 $c->path_to( 'db', 'sqlite.db' );
406
407 $c->plugin( $name, $class, @args )
408
409 Helper method for plugins. It creates a classdata accessor/mutator and
410 loads and instantiates the given class.
411
412 MyApp->plugin( 'prototype', 'HTML::Prototype' );
413
414 $c->prototype->define_javascript_functions;
415
416 MyApp->setup
417
418 Initializes the dispatcher and engine, loads any plugins, and loads the
419 model, view, and controller components. You may also specify an array
420 of plugins to load here, if you choose to not load them in the "use
421 Catalyst" line.
422
423 MyApp->setup;
424 MyApp->setup( qw/-Debug/ );
425
426 $c->uri_for( $path, @args?, \%query_values? )
427
428 Merges path with "$c->request->base" for absolute URIs and with
429 "$c->namespace" for relative URIs, then returns a normalized URI
430 object. If any args are passed, they are added at the end of the path.
431 If the last argument to "uri_for" is a hash reference, it is assumed to
432 contain GET parameter key/value pairs, which will be appended to the
433 URI in standard fashion.
434
435 Instead of $path, you can also optionally pass a $action object which
436 will be resolved to a path using "$c->dispatcher->uri_for_action"; if
437 the first element of @args is an arrayref it is treated as a list of
438 captures to be passed to "uri_for_action".
439
440 $c->welcome_message
441
442 Returns the Catalyst welcome HTML page.
443
445 These methods are not meant to be used by end users.
446
447 $c->components
448
449 Returns a hash of components.
450
451 $c->context_class
452
453 Returns or sets the context class.
454
455 $c->counter
456
457 Returns a hashref containing coderefs and execution counts (needed for
458 deep recursion detection).
459
460 $c->depth
461
462 Returns the number of actions on the current internal execution stack.
463
464 $c->dispatch
465
466 Dispatches a request to actions.
467
468 $c->dispatcher_class
469
470 Returns or sets the dispatcher class.
471
472 $c->dump_these
473
474 Returns a list of 2-element array references (name, structure) pairs
475 that will be dumped on the error page in debug mode.
476
477 $c->engine_class
478
479 Returns or sets the engine class.
480
481 $c->execute( $class, $coderef )
482
483 Execute a coderef in given class and catch exceptions. Errors are
484 available via $c->error.
485
486 $c->_localize_fields( sub { }, \%keys );
487
488 $c->finalize
489
490 Finalizes the request.
491
492 $c->finalize_body
493
494 Finalizes body.
495
496 $c->finalize_cookies
497
498 Finalizes cookies.
499
500 $c->finalize_error
501
502 Finalizes error.
503
504 $c->finalize_headers
505
506 Finalizes headers.
507
508 $c->finalize_output
509
510 An alias for finalize_body.
511
512 $c->finalize_read
513
514 Finalizes the input after reading is complete.
515
516 $c->finalize_uploads
517
518 Finalizes uploads. Cleans up any temporary files.
519
520 $c->get_action( $action, $namespace )
521
522 Gets an action in a given namespace.
523
524 $c->get_actions( $action, $namespace )
525
526 Gets all actions of a given name in a namespace and all parent names‐
527 paces.
528
529 $c->handle_request( $class, @arguments )
530
531 Called to handle each HTTP request.
532
533 $c->prepare( @arguments )
534
535 Creates a Catalyst context from an engine-specific request (Apache,
536 CGI, etc.).
537
538 $c->prepare_action
539
540 Prepares action. See Catalyst::Dispatcher.
541
542 $c->prepare_body
543
544 Prepares message body.
545
546 $c->prepare_body_chunk( $chunk )
547
548 Prepares a chunk of data before sending it to HTTP::Body.
549
550 See Catalyst::Engine.
551
552 $c->prepare_body_parameters
553
554 Prepares body parameters.
555
556 $c->prepare_connection
557
558 Prepares connection.
559
560 $c->prepare_cookies
561
562 Prepares cookies.
563
564 $c->prepare_headers
565
566 Prepares headers.
567
568 $c->prepare_parameters
569
570 Prepares parameters.
571
572 $c->prepare_path
573
574 Prepares path and base.
575
576 $c->prepare_query_parameters
577
578 Prepares query parameters.
579
580 $c->prepare_read
581
582 Prepares the input for reading.
583
584 $c->prepare_request
585
586 Prepares the engine request.
587
588 $c->prepare_uploads
589
590 Prepares uploads.
591
592 $c->prepare_write
593
594 Prepares the output for writing.
595
596 $c->request_class
597
598 Returns or sets the request class.
599
600 $c->response_class
601
602 Returns or sets the response class.
603
604 $c->read( [$maxlength] )
605
606 Reads a chunk of data from the request body. This method is designed to
607 be used in a while loop, reading $maxlength bytes on every call.
608 $maxlength defaults to the size of the request if not specified.
609
610 You have to set "MyApp->config->{parse_on_demand}" to use this
611 directly.
612
613 Warning: If you use read(), Catalyst will not process the body, so you
614 will not be able to access POST parameters or file uploads via
615 $c->request. You must handle all body parsing yourself.
616
617 $c->run
618
619 Starts the engine.
620
621 $c->set_action( $action, $code, $namespace, $attrs )
622
623 Sets an action in a given namespace.
624
625 $c->setup_actions($component)
626
627 Sets up actions for a component.
628
629 $c->setup_components
630
631 Sets up components. Specify a "setup_components" config option to pass
632 additional options directly to Module::Pluggable. To add additional
633 search paths, specify a key named "search_extra" as an array reference.
634 Items in the array beginning with "::" will have the application class
635 name prepended to them.
636
637 $c->setup_component
638
639 $c->setup_dispatcher
640
641 Sets up dispatcher.
642
643 $c->setup_engine
644
645 Sets up engine.
646
647 $c->setup_home
648
649 Sets up the home directory.
650
651 $c->setup_log
652
653 Sets up log.
654
655 $c->setup_plugins
656
657 Sets up plugins.
658
659 $c->setup_stats
660
661 Sets up timing statistics class.
662
663 $c->registered_plugins
664
665 Returns a sorted list of the plugins which have either been stated in
666 the import list or which have been added via "MyApp->plugin(@args);".
667
668 If passed a given plugin name, it will report a boolean value indicat‐
669 ing whether or not that plugin is loaded. A fully qualified name is
670 required if the plugin name does not begin with "Catalyst::Plugin::".
671
672 if ($c->registered_plugins('Some::Plugin')) {
673 ...
674 }
675
676 $c->stack
677
678 Returns an arrayref of the internal execution stack (actions that are
679 currently executing).
680
681 $c->stats_class
682
683 Returns or sets the stats (timing statistics) class.
684
685 $c->use_stats
686
687 Returns 1 when stats collection is enabled. Stats collection is
688 enabled when the -Stats options is set, debug is on or when the
689 <MYAPP>_STATS environment variable is set.
690
691 Note that this is a static method, not an accessor and should be over‐
692 loaded by declaring "sub use_stats { 1 }" in your MyApp.pm, not by
693 calling $c->use_stats(1).
694
695 $c->write( $data )
696
697 Writes $data to the output stream. When using this method directly, you
698 will need to manually set the "Content-Length" header to the length of
699 your output data, if known.
700
701 version
702
703 Returns the Catalyst version number. Mostly useful for "powered by"
704 messages in template systems.
705
707 Catalyst uses internal actions like "_DISPATCH", "_BEGIN", "_AUTO",
708 "_ACTION", and "_END". These are by default not shown in the private
709 action table, but you can make them visible with a config parameter.
710
711 MyApp->config->{show_internal_actions} = 1;
712
714 By default Catalyst is not case sensitive, so "MyApp::C::FOO::Bar" is
715 mapped to "/foo/bar". You can activate case sensitivity with a config
716 parameter.
717
718 MyApp->config->{case_sensitive} = 1;
719
720 This causes "MyApp::C::Foo::Bar" to map to "/Foo/Bar".
721
723 The request body is usually parsed at the beginning of a request, but
724 if you want to handle input yourself, you can enable on-demand parsing
725 with a config parameter.
726
727 MyApp->config->{parse_on_demand} = 1;
728
730 Many production servers operate using the common double-server
731 approach, with a lightweight frontend web server passing requests to a
732 larger backend server. An application running on the backend server
733 must deal with two problems: the remote user always appears to be
734 127.0.0.1 and the server's hostname will appear to be "localhost"
735 regardless of the virtual host that the user connected through.
736
737 Catalyst will automatically detect this situation when you are running
738 the frontend and backend servers on the same machine. The following
739 changes are made to the request.
740
741 $c->req->address is set to the user's real IP address, as read from
742 the HTTP X-Forwarded-For header.
743
744 The host value for $c->req->base and $c->req->uri is set to the real
745 host, as read from the HTTP X-Forwarded-Host header.
746
747 Obviously, your web server must support these headers for this to work.
748
749 In a more complex server farm environment where you may have your fron‐
750 tend proxy server(s) on different machines, you will need to set a con‐
751 figuration option to tell Catalyst to read the proxied data from the
752 headers.
753
754 MyApp->config->{using_frontend_proxy} = 1;
755
756 If you do not wish to use the proxy support at all, you may set:
757
758 MyApp->config->{ignore_frontend_proxy} = 1;
759
761 Catalyst has been tested under Apache 2's threading "mpm_worker",
762 "mpm_winnt", and the standalone forking HTTP server on Windows. We
763 believe the Catalyst core to be thread-safe.
764
765 If you plan to operate in a threaded environment, remember that all
766 other modules you are using must also be thread-safe. Some modules,
767 most notably DBD::SQLite, are not thread-safe.
768
770 IRC:
771
772 Join #catalyst on irc.perl.org.
773
774 Mailing Lists:
775
776 http://lists.rawmode.org/mailman/listinfo/catalyst
777 http://lists.rawmode.org/mailman/listinfo/catalyst-dev
778
779 Web:
780
781 http://catalyst.perl.org
782
783 Wiki:
784
785 http://dev.catalyst.perl.org
786
788 Task::Catalyst - All you need to start with Catalyst
789
790 Catalyst::Manual - The Catalyst Manual
791
792 Catalyst::Component, Catalyst::Base - Base classes for components
793
794 Catalyst::Engine - Core engine
795
796 Catalyst::Log - Log class.
797
798 Catalyst::Request - Request object
799
800 Catalyst::Response - Response object
801
802 Catalyst::Test - The test suite.
803
805 Andy Grundman
806
807 Andy Wardley
808
809 Andreas Marienborg
810
811 Andrew Bramble
812
813 Andrew Ford
814
815 Andrew Ruthven
816
817 Arthur Bergman
818
819 Autrijus Tang
820
821 Brian Cassidy
822
823 Carl Franks
824
825 Christian Hansen
826
827 Christopher Hicks
828
829 Dan Sully
830
831 Danijel Milicevic
832
833 David Kamholz
834
835 David Naughton
836
837 Drew Taylor
838
839 Gary Ashton Jones
840
841 Geoff Richards
842
843 Jesse Sheidlower
844
845 Jesse Vincent
846
847 Jody Belka
848
849 Johan Lindstrom
850
851 Juan Camacho
852
853 Leon Brocard
854
855 Marcus Ramberg
856
857 Matt S Trout
858
859 Robert Sedlacek
860
861 Sam Vilain
862
863 Sascha Kiefer
864
865 Sebastian Willert
866
867 Tatsuhiko Miyagawa
868
869 Ulf Edvinsson
870
871 Yuval Kogman
872
874 Sebastian Riedel, "sri@oook.de"
875
877 This library is free software, you can redistribute it and/or modify it
878 under the same terms as Perl itself.
879
880
881
882perl v5.8.8 2007-09-20 Catalyst(3)