Catalyst - The Elegant MVC Web Application Framework
See the Catalyst::Manual distribution for comprehensive documentation and tutorials.
# Install Catalyst::Devel for helpers and other development tools # use the helper to create a new application catalyst.pl MyApp # add models, views, controllers script/myapp_create.pl model MyDatabase DBIC::Schema create=static dbi:SQLite:/path/to/db script/myapp_create.pl view MyTemplate TT script/myapp_create.pl controller Search # built in testserver -- use -r to restart automatically on changes # --help to see all available options script/myapp_server.pl # command line testing interface script/myapp_test.pl /yada ### in lib/MyApp.pm use Catalyst qw/-Debug/; # include plugins here as well ### In lib/MyApp/Controller/Root.pm (autocreated) 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} = $c->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_exists ) { # Catalyst::Plugin::Authentication $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 Root 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->captures->[0]; }
See Catalyst::Manual::Intro for additional information.
Catalyst is a modern framework for making web applications without the pain usually associated with this process. This document is a reference to the main Catalyst application. If you are a new user, we suggest you start with Catalyst::Manual::Tutorial or Catalyst::Manual::Intro.
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.
Catalyst::Plugin::
Catalyst::Plugin::My::Module
My::Module
use Catalyst qw/My::Module/;
If your plugin starts with a name other than Catalyst::Plugin::, you can fully qualify the name by using a unary plus:
use Catalyst qw/ My::Module +Fully::Qualified::Plugin::Name /;
Special flags like -Debug and -Engine can also be specified as arguments when Catalyst is loaded:
-Debug
-Engine
use Catalyst qw/-Debug My::Module/;
The position of plugins and flags in the chain is important, because they are loaded in the order in which they appear.
The following flags are supported:
Enables debug output. You can also force this setting from the system environment with CATALYST_DEBUG or <MYAPP>_DEBUG. The environment settings override the application, with <MYAPP>_DEBUG having the highest priority.
Forces Catalyst to use a specific engine. Omit the Catalyst::Engine:: prefix of the engine name, i.e.:
Catalyst::Engine::
use Catalyst qw/-Engine=CGI/;
Forces Catalyst to use a specific home directory, e.g.:
use Catalyst qw[-Home=/usr/mst];
This can also be done in the shell environment by setting either the CATALYST_HOME environment variable or MYAPP_HOME; where MYAPP is replaced with the uppercased name of your application, any "::" in the name will be replaced with underscores, e.g. MyApp::Web should use MYAPP_WEB_HOME. If both variables are set, the MYAPP_HOME one will be used.
CATALYST_HOME
MYAPP_HOME
MYAPP
Specifies log level.
Enables statistics collection and reporting. You can also force this setting from the system environment with CATALYST_STATS or <MYAPP>_STATS. The environment settings override the application, with <MYAPP>_STATS having the highest priority.
e.g.
use Catalyst qw/-Stats=1/
Returns a Catalyst::Action object for the current action, which stringifies to the action name. See Catalyst::Action.
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';
Returns the current Catalyst::Request object, giving access to information about the current client request (including parameters, cookies, HTTP headers, etc.). See Catalyst::Request.
Forwards processing to another action, by its private name. 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.
process()
@_
$c->req->args
Any data returned from the action forwarded to, will be returned by the call to forward.
return
my $foodata = $c->forward('/foo'); $c->forward('index'); $c->forward(qw/MyApp::Model::DBIC::Foo do_stuff/); $c->forward('MyApp::View::TT');
Note that forward implies an <eval { }> around the call (actually execute does), thus de-fatalizing all 'dies' within the called action. If you want die to propagate you need to do something like:
<eval { }
execute
die
$c->forward('foo'); die $c->error if $c->error;
Or make sure to always return true values from your actions and write your code like this:
$c->forward('foo') || return;
The same as forward, but doesn't return to the previous action when processing is finished.
forward
When called with no arguments it escapes the processing chain entirely.
Almost the same as forward, but does a full dispatch, instead of just calling the new $action / $class->$method. This means that begin, auto and the method you go to are called, just like a new request.
$action
$class->$method
begin
auto
In addition both $c->action and $c->namespace are localized. This means, for example, that $c->action methods such as name, class and reverse return information for the visited action when they are invoked within the visited action. This is different from the behavior of forward which continues to use the $c->action object from the caller action even when invoked from the callee.
$c->action
$c->namespace
name
class
reverse
$c->stash is kept unchanged.
$c->stash
In effect, visit allows you to "wrap" another action, just as it would have been called by dispatching from a URL, while the analogous go allows you to transfer control to another action as if it had been reached directly from a URL.
visit
go
Almost the same as detach, but does a full dispatch like visit, instead of just calling the new $action / $class->$method. This means that begin, auto and the method you visit are called, just like a new request.
detach
Returns the current Catalyst::Response object, see there for details.
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 (for this you must use a session; see Catalyst::Plugin::Session for a complete system integrated with Catalyst).
$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::View::TT' );
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 only be used to store fatal error messages.
my @error = @{ $c->error };
Add a new error.
$c->error('Something bad happened');
Contains the return value of the last executed action.
Clear errors. You probably don't want to clear the errors unless you are implementing a custom error screen.
This is equivalent to running
$c->error(0);
Gets a Catalyst::Controller instance by name.
$c->controller('Foo')->do_stuff;
If the name is omitted, will return the controller for the dispatched action.
If you want to search for controllers, pass in a regexp as the argument.
# find all controllers that start with Foo my @foo_controllers = $c->controller(qr{^Foo});
Gets a Catalyst::Model instance by name.
$c->model('Foo')->do_stuff;
Any extra arguments are directly passed to ACCEPT_CONTEXT.
If the name is omitted, it will look for - a model object in $c->stash->{current_model_instance}, then - a model name in $c->stash->{current_model}, then - a config setting 'default_model', or - check if there is only one model, and return it if that's the case.
If you want to search for models, pass in a regexp as the argument.
# find all models that start with Foo my @foo_models = $c->model(qr{^Foo});
Gets a Catalyst::View instance by name.
$c->view('Foo')->do_stuff;
If the name is omitted, it will look for - a view object in $c->stash->{current_view_instance}, then - a view name in $c->stash->{current_view}, then - a config setting 'default_view', or - check if there is only one view, and return it if that's the case.
If you want to search for views, pass in a regexp as the argument.
# find all views that start with Foo my @foo_views = $c->view(qr{^Foo});
Returns the available names which can be passed to $c->controller
Returns the available names which can be passed to $c->model
Returns the available names which can be passed to $c->view
Gets a component object by name. This method is not 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
$c->model
$c->view
If $name is a regexp, a list of components matched against the full component name will be returned.
$name
Returns or takes a hashref containing the application's configuration.
__PACKAGE__->config( { db => 'dsn:SQLite:foo.db' } );
You can also use a YAML, XML or Config::General config file like myapp.yml in your applications home directory. See Catalyst::Plugin::ConfigLoader.
YAML
XML
Config::General
--- db: dsn:SQLite:foo.db
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, set the logger with the __PACKAGE__->log method prior to calling __PACKAGE__->setup.
__PACKAGE__->log
__PACKAGE__->setup
__PACKAGE__->log( MyLogger->new ); __PACKAGE__->setup;
And later:
$c->log->info( 'Now logging with my own logger!' );
Your log class should implement the methods described in Catalyst::Log.
Overload to enable debug messages (same as -Debug option).
Note that this is a static method, not an accessor and should be overloaded by declaring "sub debug { 1 }" in your MyApp.pm, not by calling $c->debug(1).
Returns the dispatcher instance. Stringifies to class name. See Catalyst::Dispatcher.
Returns the engine instance. Stringifies to the class name. See Catalyst::Engine.
Merges @path with $c->config->{home} and returns a Path::Class::Dir object.
@path
$c->config->{home}
For example:
$c->path_to( 'db', 'sqlite.db' );
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;
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.
use Catalyst
MyApp->setup; MyApp->setup( qw/-Debug/ );
A Catalyst::Action object representing the Catalyst action you want to create a URI for.
To get an action object:
From another controller, anywhere: C<< $c->controller('ControllerName')->action_for('someactionname') >> Shorter styles useful in particular places: In the current controller's action method: C<< $self->action_for('someactionname') >> From the view for currently dispatched action: C<< $c->controller->action_for('someactionname') >>
This method must be used to create URIs for Catalyst::DispatchType::Chained actions.
The actual path you wish to create a URI for, this is a public path, not a private action path.
If provided, this argument is used to insert values into a Chained action in the parts where the definitions contain CaptureArgs. If not needed, leave out this argument.
If provided, this is used as a list of further path sections to append to the URI. In a Chained action these are the equivalent to the endpoint Args.
If provided, the query_values hashref is used to add query parameters to the URI, with the keys as the names, and the values as the values.
Returns a URI object.
## Ex 1: a path with args and a query parameter $c->uri_for($c->controller('User')->action_for('list'), 'short', { page => 2}); ## -> ($c->req->base is 'http://localhost:3000/' URI->new('http://localhost:3000/user/list/short?page=2) ## Ex 2: a chained view action that captures the user id ## In controller: sub user : Chained('/'): PathPart('myuser'): CaptureArgs(1) {} sub viewuser : Chained('user'): PathPart('view') {} ## In uri creating code: my $uaction = $c->controller('Users')->action_for('viewuser'); $c->uri_for($uaction, [ 42 ]); ## outputs: URI->new('http://localhost:3000/myuser/42/view') ## Ex 3: this style is deprecated and should be omitted $c->uri_for('user/list', 'short', { page => 2}); ## -> ($c->req->base is 'http://localhost:3000/' URI->new('http://localhost:3000/user/list/short?page=2)
Creates a URI object using $c->request->base and a path. If an Action object is given instead of a path, the path is constructed using $c->dispatcher->uri_for_action and passing it the @captures array, if supplied.
$c->request->base
$c->dispatcher->uri_for_action
If any query parameters are passed they are added to the end of the URI in the usual way.
Note that uri_for is destructive to the passed query values hashref. Subsequent calls with the same hashref may have unintended results.
Returns the Catalyst welcome HTML page.
These methods are not meant to be used by end users.
Returns a hash of components.
Returns or sets the context class.
Returns a hashref containing coderefs and execution counts (needed for deep recursion detection).
Returns the number of actions on the current internal execution stack.
Dispatches a request to actions.
Returns or sets the dispatcher class.
Returns a list of 2-element array references (name, structure) pairs that will be dumped on the error page in debug mode.
Returns or sets the engine class.
Execute a coderef in given class and catch exceptions. Errors are available via $c->error.
Finalizes the request.
Finalizes body.
Finalizes cookies.
Finalizes error.
Finalizes headers.
An alias for finalize_body.
Finalizes the input after reading is complete.
Finalizes uploads. Cleans up any temporary files.
Gets an action in a given namespace.
Gets all actions of a given name in a namespace and all parent namespaces.
Called to handle each HTTP request.
Creates a Catalyst context from an engine-specific request (Apache, CGI, etc.).
Prepares action. See Catalyst::Dispatcher.
Prepares message body.
Prepares a chunk of data before sending it to HTTP::Body.
See Catalyst::Engine.
Prepares body parameters.
Prepares connection.
Prepares cookies.
Prepares headers.
Prepares parameters.
Prepares path and base.
Prepares query parameters.
Prepares the input for reading.
Prepares the engine request.
Prepares uploads.
Prepares the output for writing.
Returns or sets the request class.
Returns or sets the response class.
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.
$maxlength
You have to set MyApp->config->{parse_on_demand} to use this directly.
MyApp->config->{parse_on_demand}
Warning: If you use read(), Catalyst will not process the body, so you will not be able to access POST parameters or file uploads via $c->request. You must handle all body parsing yourself.
Starts the engine.
Sets an action in a given namespace.
Sets up actions for a component.
Sets up components. Specify a setup_components config option to pass additional options directly to Module::Pluggable. To add additional search paths, specify a key named search_extra as an array reference. Items in the array beginning with :: will have the application class name prepended to them.
setup_components
search_extra
::
All components found will also have any Devel::InnerPackage loaded and set up as components. Note, that modules which are not an inner package of the main file namespace loaded will not be instantiated as components.
Sets up dispatcher.
Sets up engine.
Sets up the home directory.
Sets up log.
Sets up plugins.
Sets up timing statistics class.
Returns a sorted list of the plugins which have either been stated in the import list or which have been added via MyApp->plugin(@args);.
MyApp->plugin(@args);
If passed a given plugin name, it will report a boolean value indicating whether or not that plugin is loaded. A fully qualified name is required if the plugin name does not begin with Catalyst::Plugin::.
if ($c->registered_plugins('Some::Plugin')) { ... }
Returns an arrayref of the internal execution stack (actions that are currently executing).
Returns or sets the stats (timing statistics) class.
Returns 1 when stats collection is enabled. Stats collection is enabled when the -Stats options is set, debug is on or when the <MYAPP>_STATS environment variable is set.
Note that this is a static method, not an accessor and should be overloaded by declaring "sub use_stats { 1 }" in your MyApp.pm, not by calling $c->use_stats(1).
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.
Content-Length
Returns the Catalyst version number. Mostly useful for "powered by" messages in template systems.
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.
_DISPATCH
_BEGIN
_AUTO
_ACTION
_END
MyApp->config->{show_internal_actions} = 1;
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::C::FOO::Bar
/foo/bar
MyApp->config->{case_sensitive} = 1;
This causes MyApp::C::Foo::Bar to map to /Foo/Bar.
MyApp::C::Foo::Bar
/Foo/Bar
The request body is usually parsed at the beginning of a request, but if you want to handle input yourself, you can enable on-demand parsing with a config parameter.
MyApp->config->{parse_on_demand} = 1;
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.
127.0.0.1
localhost
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;
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.
mpm_worker
mpm_winnt
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.
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
sri: Sebastian Riedel <sri@cpan.org>
abw: Andy Wardley
acme: Leon Brocard <leon@astray.com>
Andrew Bramble
Andrew Ford
Andrew Ruthven
andyg: Andy Grundman <andy@hybridized.org>
audreyt: Audrey Tang
bricas: Brian Cassidy <bricas@cpan.org>
chansen: Christian Hansen
chicks: Christopher Hicks
dkubb: Dan Kubb <dan.kubb-cpan@onautopilot.com>
Drew Taylor
esskar: Sascha Kiefer
fireartist: Carl Franks <cfranks@cpan.org>
gabb: Danijel Milicevic
Gary Ashton Jones
Geoff Richards
jcamacho: Juan Camacho
jhannah: Jay Hannah <jay@jays.net>
Jody Belka
Johan Lindstrom
jon: Jon Schutz <jjschutz@cpan.org>
marcus: Marcus Ramberg <mramberg@cpan.org>
miyagawa: Tatsuhiko Miyagawa <miyagawa@bulknews.net>
mst: Matt S. Trout <mst@shadowcatsystems.co.uk>
mugwump: Sam Vilain
naughton: David Naughton
ningu: David Kamholz <dkamholz@cpan.org>
nothingmuch: Yuval Kogman <nothingmuch@woobling.org>
numa: Dan Sully <daniel@cpan.org>
obra: Jesse Vincent
omega: Andreas Marienborg
Oleg Kostyuk <cub.uanic@gmail.com>
phaylon: Robert Sedlacek <phaylon@dunkelheit.at>
sky: Arthur Bergman
the_jester: Jesse Sheidlower
Ulf Edvinsson
willert: Sebastian Willert <willert@cpan.org>
batman: Jan Henning Thorsen <pm@flodhest.net>
This library is free software, you can redistribute it and/or modify it under the same terms as Perl itself.
To install Catalyst::Runtime, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Catalyst::Runtime
CPAN shell
perl -MCPAN -e shell install Catalyst::Runtime
For more information on module installation, please visit the detailed CPAN module installation guide.