SYNOPSIS
# use the helper to start a new application
catalyst.pl MyApp
- cd MyApp
# add models, views, controllers
- script/myapp_create.pl model Something
- script/myapp_create.pl view Stuff
- script/myapp_create.pl controller Yada
+ 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
+ # built in testserver -- use -r to restart automatically on changes
script/myapp_server.pl
- # command line interface
+ # command line testing interface
script/myapp_test.pl /yada
- use Catalyst;
-
- use Catalyst qw/My::Module My::OtherModule/;
-
- use Catalyst '-Debug';
-
- use Catalyst qw/-Debug -Engine=CGI/;
-
- sub default : Private { $_[1]->res->output('Hello') } );
+ ### 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/on you/ for /foo/on/you
+ $c->stash->{template} = 'foo.tt';
+ # lookup something from db -- stash vars are passed to TT
+ $c->stash->{data} = MyApp::Model::Database::Foo->search;
+ 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 easily 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') { ... }
- sub index : Path('/index.html') {
+ # called for all actions, from the top-most controller inwards
+ sub auto : Private {
my ( $self, $c ) = @_;
- $c->res->output('Hello');
- $c->forward('foo');
+ if ( !$c->user ) {
+ $c->res->redirect( '/login' ); # require login
+ return 0; # abort request and go immediately to end()
+ }
+ return 1;
+ }
+
+ # called after the main action is 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
}
- sub product : Regex('^product[_]*(\d*).html$') {
+ ### 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 ) = @_;
- $c->stash->{template} = 'product.tt';
- $c->stash->{product} = $c->req->snippets->[0];
+ # extract the (\w+) from the URI
+ my $product = $c->req->snippets->[0];
}
- See also Catalyst::Manual::Intro
+ See Catalyst::Manual::Intro for additional information.
DESCRIPTION
The key concept of Catalyst is DRY (Don't Repeat Yourself).
Catalyst plugins can be loaded by naming them as arguments to the "use
Catalyst" statement. Omit the "Catalyst::Plugin::" prefix from the
- plugin name, so "Catalyst::Plugin::My::Module" becomes "My::Module".
+ plugin name, i.e., "Catalyst::Plugin::My::Module" becomes "My::Module".
- use Catalyst 'My::Module';
+ use Catalyst qw/My::Module/;
Special flags like -Debug and -Engine can also be specified as arguments
when Catalyst is loaded:
The following flags are supported:
-Debug
- enables debug output, i.e.:
-
- use Catalyst '-Debug';
-
- this is equivalent to:
-
- use Catalyst;
- sub debug { 1 }
-
- -Dispatcher
- Force Catalyst to use a specific dispatcher.
+ Enables debug output.
-Engine
- Force Catalyst to use a specific engine. Omit the
+ Forces Catalyst to use a specific engine. Omit the
"Catalyst::Engine::" prefix of the engine name, i.e.:
- use Catalyst '-Engine=CGI';
+ use Catalyst qw/-Engine=CGI/;
-Home
- Force Catalyst to use a specific home directory.
+ Forces Catalyst to use a specific home directory.
-Log
- Specify log level.
+ Specifies log level.
METHODS
+ Information about the current request
$c->action
- Accessor for the current action
-
- $c->comp($name)
- $c->component($name)
- Get a component object by name.
-
- $c->comp('MyApp::Model::MyModel')->do_stuff;
-
- config
- Returns a hashref containing your applications settings.
-
- $c->controller($name)
- Get a Catalyst::Controller instance by name.
-
- $c->controller('Foo')->do_stuff;
+ Returns a Catalyst::Action object for the current action, which
+ stringifies to the action name.
- debug
- Overload to enable debug messages.
-
- $c->detach( $command [, \@arguments ] )
- Like "forward" but doesn't return.
+ $c->namespace
+ Returns the namespace of the current action, i.e., the uri prefix
+ corresponding to the controller of the current action.
- $c->dispatcher
- Contains the dispatcher instance. Stringifies to class.
+ $c->request
+ $c->req
+ Returns the current Catalyst::Request object.
- $c->forward( $command [, \@arguments ] )
- Forward processing to a private action or a method from a class. If
- you define a class without method it will default to process(). also
- takes an optional arrayref containing arguments to be passed to the
- new function. $c->req->args will be reset upon returning from the
- function.
+ 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->model($name)
- Get a Catalyst::Model instance by name.
-
- $c->model('Foo')->do_stuff;
-
- $c->namespace
- Accessor to the namespace of the current action
-
- $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->setup
- Setup.
-
- $c->setup;
-
- $c->uri_for($path,[@args])
- Merges path with $c->request->base for absolute uri's and with
- $c->request->match 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->detach( $action [, \@arguments ] )
+ $c->detach( $class, $method, [, \@arguments ] )
+ The same as "forward", but doesn't return.
$c->error
$c->error($error, ...)
$c->error('Something bad happened');
- Clean errors.
+ Clear errors.
$c->error(0);
- $c->engine
- Contains the engine instance. Stringifies to the class.
+ $c->response
+ $c->res
+ Returns the current Catalyst::Response object.
- $c->log
- Contains the logging object. Unless it is already set Catalyst sets
- this up with a "Catalyst::Log" object. To use your own log class:
+ $c->stash
+ Returns a hashref to the stash, which may be used to store data and
+ pass it between components. You can also set hash keys by passing
+ arguments. The stash is automatically sent to the view.
- $c->log( MyLogger->new );
- $c->log->info("now logging with my own logger!");
+ $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' );
- Your log class should implement the methods described in the
- "Catalyst::Log" man page.
+ $c->state
+ Contains the return value of the last executed action.
- $c->plugin( $name, $class, @args )
- Instant plugins for Catalyst. Classdata accessor/mutator will be
- created, class loaded and instantiated.
+ Component Accessors
+ $c->comp($name)
+ $c->component($name)
+ Gets a component object by name. This method is no longer
+ recommended. $c->controller, $c->model, and $c->view should be used
+ instead.
- MyApp->plugin( 'prototype', 'HTML::Prototype' );
+ $c->controller($name)
+ Gets a Catalyst::Controller instance by name.
- $c->prototype->define_javascript_functions;
+ $c->controller('Foo')->do_stuff;
- $c->request
- $c->req
- Returns a "Catalyst::Request" object.
+ $c->model($name)
+ Gets a Catalyst::Model instance by name.
- my $req = $c->req;
+ $c->model('Foo')->do_stuff;
- $c->response
- $c->res
- Returns a "Catalyst::Response" object.
+ $c->view($name)
+ Gets a Catalyst::View instance by name.
+
+ $c->view('Foo')->do_stuff;
- my $res = $c->res;
+ Class data and helper classes
+ $c->config
+ Returns or takes a hashref containing the application's
+ configuration.
- $c->state
- Contains the return value of the last executed action.
+ __PACKAGE__->config({ db => 'dsn:SQLite:foo.db' });
- $c->stash
- Returns a hashref containing all your data.
+ $c->debug
+ Overload to enable debug messages (same as -Debug option).
+
+ $c->dispatcher
+ Returns the dispatcher instance. Stringifies to class name.
+
+ $c->engine
+ Returns the engine instance. Stringifies to the class name.
+
+ $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:
- print $c->stash->{foo};
+ $c->log( MyLogger->new );
+ $c->log->info( 'now logging with my own logger!' );
- Keys may be set in the stash by assigning to the hash reference, or
- by passing either a single hash reference or a list of key/value
- pairs as arguments.
+ 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->stash->{foo} ||= 'yada';
- $c->stash( { moose => 'majestic', qux => 0 } );
- $c->stash( bar => 1, gorch => 2 );
+ $c->path_to( 'db', 'sqlite.db' );
- $c->view($name)
- Get a Catalyst::View instance by name.
+ $c->plugin( $name, $class, @args )
+ Helper method for plugins. It creates a classdata accessor/mutator
+ and loads and instantiates the given class.
- $c->view('Foo')->do_stuff;
+ 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->request->match 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
- $c->benchmark($coderef)
+ $c->benchmark( $coderef )
Takes a coderef with arguments and returns elapsed time as float.
my ( $elapsed, $status ) = $c->benchmark( sub { return 1 } );
$c->log->info( sprintf "Processing took %f seconds", $elapsed );
$c->components
- Contains the components.
+ Returns a hash of components.
- $c->context_class($class)
- Contains the context class.
+ $c->context_class
+ Returns or sets the context class.
$c->counter
- Returns a hashref containing coderefs and execution counts. (Needed
- for deep recursion detection)
+ Returns a hashref containing coderefs and execution counts (needed
+ for deep recursion detection).
$c->depth
- Returns the actual forward depth.
+ Returns the number of actions on the current internal execution
+ stack.
$c->dispatch
- Dispatch request to actions.
+ Dispatches a request to actions.
- $c->dispatcher_class($class)
- Contains the dispatcher class.
+ $c->dispatcher_class
+ Returns or sets the dispatcher class.
- dump_these
+ $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($class)
- Contains the engine class.
+ $c->engine_class
+ Returns or sets the engine class.
- $c->execute($class, $coderef)
+ $c->execute( $class, $coderef )
Execute a coderef in given class and catch exceptions. Errors are
available via $c->error.
$c->finalize
- Finalize request.
+ Finalizes the request.
$c->finalize_body
- Finalize body.
+ Finalizes body.
$c->finalize_cookies
- Finalize cookies.
+ Finalizes cookies.
$c->finalize_error
- Finalize error.
+ Finalizes error.
$c->finalize_headers
- Finalize headers.
+ Finalizes headers.
$c->finalize_output
An alias for finalize_body.
$c->finalize_read
- Finalize the input after reading is complete.
+ Finalizes the input after reading is complete.
$c->finalize_uploads
- Finalize uploads. Cleans up any temporary files.
+ Finalizes uploads. Cleans up any temporary files.
$c->get_action( $action, $namespace )
- Get an action in a given namespace.
+ Gets an action in a given namespace.
$c->get_actions( $action, $namespace )
- Get all actions of a given name in a namespace and all base
+ Gets all actions of a given name in a namespace and all parent
namespaces.
handle_request( $class, @arguments )
- Handles the request.
+ Called to handle each HTTP request.
- $c->prepare(@arguments)
- Turns the engine-specific request( Apache, CGI ... ) into a Catalyst
- context .
+ $c->prepare( @arguments )
+ Creates a Catalyst context from an engine-specific request (Apache,
+ CGI, etc.).
$c->prepare_action
- Prepare action.
+ Prepares action.
$c->prepare_body
- Prepare message body.
+ Prepares message body.
$c->prepare_body_chunk( $chunk )
- Prepare a chunk of data before sending it to HTTP::Body.
+ Prepares a chunk of data before sending it to HTTP::Body.
$c->prepare_body_parameters
- Prepare body parameters.
+ Prepares body parameters.
$c->prepare_connection
- Prepare connection.
+ Prepares connection.
$c->prepare_cookies
- Prepare cookies.
+ Prepares cookies.
$c->prepare_headers
- Prepare headers.
+ Prepares headers.
$c->prepare_parameters
- Prepare parameters.
+ Prepares parameters.
$c->prepare_path
- Prepare path and base.
+ Prepares path and base.
$c->prepare_query_parameters
- Prepare query parameters.
+ Prepares query parameters.
$c->prepare_read
- Prepare the input for reading.
+ Prepares the input for reading.
$c->prepare_request
- Prepare the engine request.
+ Prepares the engine request.
$c->prepare_uploads
- Prepare uploads.
+ Prepares uploads.
$c->prepare_write
- Prepare the output for writing.
+ Prepares the output for writing.
- $c->request_class($class)
- Contains the request class.
+ $c->request_class
+ Returns or sets the request class.
- $c->response_class($class)
- Contains the response class.
+ $c->response_class
+ Returns or sets the response class.
$c->read( [$maxlength] )
- Read a chunk of data from the request body. This method is designed
+ 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.
Starts the engine.
$c->set_action( $action, $code, $namespace, $attrs )
- Set an action in a given namespace.
+ Sets an action in a given namespace.
$c->setup_actions($component)
- Setup actions for a component.
+ Sets up actions for a component.
$c->setup_components
- Setup components.
+ Sets up components.
$c->setup_dispatcher
$c->setup_engine
$c->setup_log
$c->setup_plugins
$c->stack
- Contains the stack.
+ Returns the stack.
$c->write( $data )
Writes $data to the output stream. When using this method directly,
length of your output data, if known.
version
- Returns the Catalyst version number. mostly useful for powered by
+ 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 deactivate this with a config parameter.
+ "_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"
- becomes "/foo/bar".
-
- But you can activate case sensitivity with a config parameter.
+ 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;
- So "MyApp::C::Foo::Bar" becomes "/Foo/Bar".
+ 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
+ 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;
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 the user connected through.
+ 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
- both the frontend and backend servers on the same machine. The following
+ 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.
+ 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.
+ as read from the HTTP X-Forwarded-Host header.
- Obviously, your web server must support these 2 headers for this to
- work.
+ 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
Join #catalyst on irc.perl.org.
- Mailing-Lists:
+ Mailing Lists:
http://lists.rawmode.org/mailman/listinfo/catalyst
http://lists.rawmode.org/mailman/listinfo/catalyst-dev
http://catalyst.perl.org
+ Wiki:
+
+ http://dev.catalyst.perl.org
+
SEE ALSO
Catalyst::Manual - The Catalyst Manual
+ Catalyst::Component, Catalyst::Base - Base classes for components
Catalyst::Engine - Core Engine
Catalyst::Log - The Log Class.
Catalyst::Request - The Request Object
Danijel Milicevic
+ David Kamholz
+
David Naughton
Gary Ashton Jones