NAME
Catalyst - The Elegant MVC Web Application Framework
SYNOPSIS
# use the helper to start a new application
catalyst.pl MyApp
# add models, views, controllers
script/myapp_create.pl model Database DBIC dbi:SQLite:/path/to/db
script/myapp_create.pl view TT TT
script/myapp_create.pl controller Search
# built in testserver -- use -r to restart automatically on changes
script/myapp_server.pl
# command line testing interface
script/myapp_test.pl /yada
### in MyApp.pm
use Catalyst qw/-Debug/; # include plugins here as well
sub foo : Global { # called for /foo, /foo/1, /foo/1/2, etc.
my ( $self, $c, @args ) = @_; # args are qw/1 2/ for /foo/1/2
$c->stash->{template} = 'foo.tt'; # set the template
# lookup something from db -- stash vars are passed to TT
$c->stash->{data} =
MyApp::Model::Database::Foo->search( { country => $args[0] } );
if ( $c->req->params->{bar} ) { # access GET or POST parameters
$c->forward( 'bar' ); # process another action
# do something else after forward returns
}
}
# The foo.tt TT template can use the stash data from the database
[% WHILE (item = data.next) %]
[% item.foo %]
[% END %]
# called for /bar/of/soap, /bar/of/soap/10, etc.
sub bar : Path('/bar/of/soap') { ... }
# called for all actions, from the top-most controller downwards
sub auto : Private {
my ( $self, $c ) = @_;
if ( !$c->user ) {
$c->res->redirect( '/login' ); # require login
return 0; # abort request and go immediately to end()
}
return 1; # success; carry on to next action
}
# called after all actions are finished
sub end : Private {
my ( $self, $c ) = @_;
if ( scalar @{ $c->error } ) { ... } # handle errors
return if $c->res->body; # already have a response
$c->forward( 'MyApp::View::TT' ); # render template
}
### in MyApp/Controller/Foo.pm
# called for /foo/bar
sub bar : Local { ... }
# called for /blargle
sub blargle : Global { ... }
# an index action matches /foo, but not /foo/1, etc.
sub index : Private { ... }
### in MyApp/Controller/Foo/Bar.pm
# called for /foo/bar/baz
sub baz : Local { ... }
# first MyApp auto is called, then Foo auto, then this
sub auto : Private { ... }
# powerful regular expression paths are also possible
sub details : Regex('^product/(\w+)/details$') {
my ( $self, $c ) = @_;
# extract the (\w+) from the URI
my $product = $c->req->snippets->[0];
}
See Catalyst::Manual::Intro for additional information.
DESCRIPTION
The key concept of Catalyst is DRY (Don't Repeat Yourself).
See Catalyst::Manual for more documentation.
Catalyst plugins can be loaded by naming them as arguments to the "use Catalyst" statement. Omit the Catalyst::Plugin::
prefix from the plugin name, i.e., Catalyst::Plugin::My::Module
becomes My::Module
.
use Catalyst qw/My::Module/;
Special flags like -Debug
and -Engine
can also be specified as arguments when Catalyst is loaded:
use Catalyst qw/-Debug My::Module/;
The position of plugins and flags in the chain is important, because they are loaded in exactly the order in which they appear.
The following flags are supported:
-Debug
Enables debug output.
-Engine
Forces Catalyst to use a specific engine. Omit the Catalyst::Engine::
prefix of the engine name, i.e.:
use Catalyst qw/-Engine=CGI/;
-Home
Forces Catalyst to use a specific home directory, e.g.:
use Catalyst qw[-Home=/usr/sri];
-Log
Specifies log level.
METHODS
Information about the current request
$c->action
Returns a Catalyst::Action object for the current action, which stringifies to the action name. See Catalyst::Action.
$c->namespace
Returns the namespace of the current action, i.e., the uri prefix corresponding to the controller of the current action. For example:
# in Controller::Foo::Bar
$c->namespace; # returns 'foo/bar';
$c->request
$c->req
Returns the current Catalyst::Request object. See Catalyst::Request.
Processing and response to the current request
$c->forward( $action [, \@arguments ] )
$c->forward( $class, $method, [, \@arguments ] )
Forwards processing to a private action. If you give a class name but no method, process()
is called. You may also optionally pass arguments in an arrayref. The action will receive the arguments in @_
and $c->req->args
. Upon returning from the function, $c->req->args
will be restored to the previous values.
$c->forward('/foo');
$c->forward('index');
$c->forward(qw/MyApp::Model::CDBI::Foo do_stuff/);
$c->forward('MyApp::View::TT');
$c->detach( $action [, \@arguments ] )
$c->detach( $class, $method, [, \@arguments ] )
The same as forward
, but doesn't return.
$c->error
$c->error($error, ...)
$c->error($arrayref)
Returns an arrayref containing error messages. If Catalyst encounters an error while processing a request, it stores the error in $c->error. This method should not be used to store non-fatal error messages.
my @error = @{ $c->error };
Add a new error.
$c->error('Something bad happened');
Clear errors. You probably don't want to clear the errors unless you are implementing a custom error screen.
$c->error(0);
$c->response
$c->res
Returns the current Catalyst::Response object.
$c->stash
Returns a hashref to the stash, which may be used to store data and pass it between components during a request. You can also set hash keys by passing arguments. The stash is automatically sent to the view. The stash is cleared at the end of a request; it cannot be used for persistent storage.
$c->stash->{foo} = $bar;
$c->stash( { moose => 'majestic', qux => 0 } );
$c->stash( bar => 1, gorch => 2 ); # equivalent to passing a hashref
# stash is automatically passed to the view for use in a template
$c->forward( 'MyApp::V::TT' );
$c->state
Contains the return value of the last executed action.
Component Accessors
$c->comp($name)
$c->component($name)
Gets a component object by name. This method is no longer recommended, unless you want to get a specific component by full class. $c->controller
, $c->model
, and $c->view
should be used instead.
$c->controller($name)
Gets a Catalyst::Controller instance by name.
$c->controller('Foo')->do_stuff;
$c->model($name)
Gets a Catalyst::Model instance by name.
$c->model('Foo')->do_stuff;
$c->view($name)
Gets a Catalyst::View instance by name.
$c->view('Foo')->do_stuff;
Class data and helper classes
$c->config
Returns or takes a hashref containing the application's configuration.
__PACKAGE__->config({ db => 'dsn:SQLite:foo.db' });
$c->debug
Overload to enable debug messages (same as -Debug option).
$c->dispatcher
Returns the dispatcher instance. Stringifies to class name. See Catalyst::Dispatcher.
$c->engine
Returns the engine instance. Stringifies to the class name. See Catalyst::Engine.
$c->log
Returns the logging object instance. Unless it is already set, Catalyst sets this up with a Catalyst::Log object. To use your own log class:
$c->log( MyLogger->new );
$c->log->info( 'Now logging with my own logger!' );
Your log class should implement the methods described in the Catalyst::Log man page.
Utility methods
$c->path_to(@path)
Merges @path
with $c->config->{home}
and returns a Path::Class object.
For example:
$c->path_to( 'db', 'sqlite.db' );
$c->plugin( $name, $class, @args )
Helper method for plugins. It creates a classdata accessor/mutator and loads and instantiates the given class.
MyApp->plugin( 'prototype', 'HTML::Prototype' );
$c->prototype->define_javascript_functions;
MyApp->setup
Initializes the dispatcher and engine, loads any plugins, and loads the model, view, and controller components. You may also specify an array of plugins to load here, if you choose to not load them in the use Catalyst
line.
MyApp->setup;
MyApp->setup( qw/-Debug/ );
$c->uri_for( $path, [ @args ] )
Merges path with $c->request->base
for absolute uri's and with $c->namespace
for relative uri's, then returns a normalized URI object. If any args are passed, they are added at the end of the path.
$c->welcome_message
Returns the Catalyst welcome HTML page.
INTERNAL METHODS
These methods are not meant to be used by end users.
$c->components
Returns a hash of components.
$c->context_class
Returns or sets the context class.
$c->counter
Returns a hashref containing coderefs and execution counts (needed for deep recursion detection).
$c->depth
Returns the number of actions on the current internal execution stack.
$c->dispatch
Dispatches a request to actions.
$c->dispatcher_class
Returns or sets the dispatcher class.
$c->dump_these
Returns a list of 2-element array references (name, structure) pairs that will be dumped on the error page in debug mode.
$c->engine_class
Returns or sets the engine class.
$c->execute( $class, $coderef )
Execute a coderef in given class and catch exceptions. Errors are available via $c->error.
$c->finalize
Finalizes the request.
$c->finalize_body
Finalizes body.
$c->finalize_cookies
Finalizes cookies.
$c->finalize_error
Finalizes error.
$c->finalize_headers
Finalizes headers.
$c->finalize_output
An alias for finalize_body.
$c->finalize_read
Finalizes the input after reading is complete.
$c->finalize_uploads
Finalizes uploads. Cleans up any temporary files.
$c->get_action( $action, $namespace )
Gets an action in a given namespace.
$c->get_actions( $action, $namespace )
Gets all actions of a given name in a namespace and all parent namespaces.
handle_request( $class, @arguments )
Called to handle each HTTP request.
$c->prepare( @arguments )
Creates a Catalyst context from an engine-specific request (Apache, CGI, etc.).
$c->prepare_action
Prepares action.
$c->prepare_body
Prepares message body.
$c->prepare_body_chunk( $chunk )
Prepares a chunk of data before sending it to HTTP::Body.
$c->prepare_body_parameters
Prepares body parameters.
$c->prepare_connection
Prepares connection.
$c->prepare_cookies
Prepares cookies.
$c->prepare_headers
Prepares headers.
$c->prepare_parameters
Prepares parameters.
$c->prepare_path
Prepares path and base.
$c->prepare_query_parameters
Prepares query parameters.
$c->prepare_read
Prepares the input for reading.
$c->prepare_request
Prepares the engine request.
$c->prepare_uploads
Prepares uploads.
$c->prepare_write
Prepares the output for writing.
$c->request_class
Returns or sets the request class.
$c->response_class
Returns or sets the response class.
$c->read( [$maxlength] )
Reads a chunk of data from the request body. This method is designed to be used in a while loop, reading $maxlength
bytes on every call. $maxlength
defaults to the size of the request if not specified.
You have to set MyApp->config->{parse_on_demand}
to use this directly.
$c->run
Starts the engine.
$c->set_action( $action, $code, $namespace, $attrs )
Sets an action in a given namespace.
$c->setup_actions($component)
Sets up actions for a component.
$c->setup_components
Sets up components.
$c->setup_dispatcher
Sets up dispatcher.
$c->setup_engine
Sets up engine.
$c->setup_home
Sets up the home directory.
$c->setup_log
Sets up log.
$c->setup_plugins
Sets up plugins.
$c->stack
Returns the stack.
$c->write( $data )
Writes $data to the output stream. When using this method directly, you will need to manually set the Content-Length
header to the length of your output data, if known.
version
Returns the Catalyst version number. Mostly useful for "powered by" messages in template systems.
INTERNAL ACTIONS
Catalyst uses internal actions like _DISPATCH
, _BEGIN
, _AUTO
, _ACTION
, and _END
. These are by default not shown in the private action table, but you can make them visible with a config parameter.
MyApp->config->{show_internal_actions} = 1;
CASE SENSITIVITY
By default Catalyst is not case sensitive, so MyApp::C::FOO::Bar
is mapped to /foo/bar
. You can activate case sensitivity with a config parameter.
MyApp->config->{case_sensitive} = 1;
This causes MyApp::C::Foo::Bar
to map to /Foo/Bar
.
ON-DEMAND PARSER
The request body is usually parsed at the beginning of a request, but if you want to handle input yourself or speed things up a bit, you can enable on-demand parsing with a config parameter.
MyApp->config->{parse_on_demand} = 1;
PROXY SUPPORT
Many production servers operate using the common double-server approach, with a lightweight frontend web server passing requests to a larger backend server. An application running on the backend server must deal with two problems: the remote user always appears to be 127.0.0.1
and the server's hostname will appear to be localhost
regardless of the virtual host that the user connected through.
Catalyst will automatically detect this situation when you are running the frontend and backend servers on the same machine. The following changes are made to the request.
$c->req->address is set to the user's real IP address, as read from
the HTTP X-Forwarded-For header.
The host value for $c->req->base and $c->req->uri is set to the real
host, as read from the HTTP X-Forwarded-Host header.
Obviously, your web server must support these headers for this to work.
In a more complex server farm environment where you may have your frontend proxy server(s) on different machines, you will need to set a configuration option to tell Catalyst to read the proxied data from the headers.
MyApp->config->{using_frontend_proxy} = 1;
If you do not wish to use the proxy support at all, you may set:
MyApp->config->{ignore_frontend_proxy} = 1;
THREAD SAFETY
Catalyst has been tested under Apache 2's threading mpm_worker, mpm_winnt, and the standalone forking HTTP server on Windows. We believe the Catalyst core to be thread-safe.
If you plan to operate in a threaded environment, remember that all other modules you are using must also be thread-safe. Some modules, most notably DBD::SQLite, are not thread-safe.
SUPPORT
IRC:
Join #catalyst on irc.perl.org.
Mailing Lists:
http://lists.rawmode.org/mailman/listinfo/catalyst
http://lists.rawmode.org/mailman/listinfo/catalyst-dev
Web:
http://catalyst.perl.org
Wiki:
http://dev.catalyst.perl.org
SEE ALSO
Task::Catalyst - All you need to start with Catalyst
Catalyst::Manual - The Catalyst Manual
Catalyst::Component, Catalyst::Base - Base classes for components
Catalyst::Engine - Core engine
Catalyst::Log - Log class.
Catalyst::Request - Request object
Catalyst::Response - Response object
Catalyst::Test - The test suite.
CREDITS
Andy Grundman
Andy Wardley
Andreas Marienborg
Andrew Bramble
Andrew Ford
Andrew Ruthven
Arthur Bergman
Autrijus Tang
Brian Cassidy
Christian Hansen
Christopher Hicks
Dan Sully
Danijel Milicevic
David Kamholz
David Naughton
Drew Taylor
Gary Ashton Jones
Geoff Richards
Jesse Sheidlower
Jesse Vincent
Jody Belka
Johan Lindstrom
Juan Camacho
Leon Brocard
Marcus Ramberg
Matt S Trout
Robert Sedlacek
Sam Vilain
Sascha Kiefer
Tatsuhiko Miyagawa
Ulf Edvinsson
Yuval Kogman
AUTHOR
Sebastian Riedel, sri@oook.de
LICENSE
This library is free software, you can redistribute it and/or modify it under the same terms as Perl itself.