An Introduction to Application Development with Catalyst and Perl

Plugins and Application-Wide Settings

Besides pre-built component classes for drop-in functionality, many plugins are available to modify the behavior and extend the functionality of Catalyst itself. A few of the most common are the optional authentication, authorization and session plugins.

These plugins provide a consistent API for handling these tasks with a variety of available back ends. Like the core request/response object interfaces, they are available as application-wide features that are accessed and controlled through methods in the context object, which become available once these plugins have been loaded.

You can authenticate a user (within an action handling a login form post, for example) like this:


$c->authenticate({
   username => $c->request->params->{username},
   password => $c->request->params->{password}
});

If this succeeds, the $c->user object is available in subsequent requests to control and direct application flow based on the authenticated user. This is accomplished using sessions (usually cookie-based) that are handled for you automatically. You also have access to $c->session to persist any additional per-session data across requests.

The API of this framework is agnostic to the back end, and many are available. You can handle authentication and user storage via databases (DBIC), system accounts, PAM and LDAP, to name a few. There also are multiple ways to handle session data to support different application needs, such as distributed server deployments and so on. (See the documentation for Catalyst::Plugin::Authentication, Catalyst::Plugin::Authorization and Catalyst::Plugin::Session for more information.)

Plugins and application-wide settings are configured within the main/core class (lib/KillerApp.pm). Within this file, you can specify global configuration parameters, load Plugins and even add your own code to override and extend core functionality.

The top-level "KillerApp" class actually is the application—it programmatically loads and integrates the other components and classes throughout the system. Like any derived class, its behaviors can be selectively altered from that of its parent class ("Catalyst"). Since it uses the powerful "Moose" object system, in addition to adding and replacing methods, you also can take advantage of additional powerful features like method modifiers and Roles (in fact, Plugins are essentially Moose Roles applied to this class).

Catalyst was written with customization and extensibility in mind. It's structured to allow its functions and behaviors to be modified easily in a fine-grained manner.

For example, you could configure every response to be set with "no-cache" across the whole application simply by adding a method modifier like this to lib/KillerApp.pm:


before 'finalize_headers' => sub {
        my $c = shift;
        $c->response->headers->header( 'Cache-control' => 'no-cache' );
};

Catalyst calls methods with meaningful names (such as 'finalize_headers') throughout the various stages of processing that you are free to hook into or override.

Deploying Your Application

Like most things in Catalyst, many options are available when you're ready to deploy your application to a real Web server—Apache/FastCGI is one of the best choices available. I briefly cover this below.

If you put your application in /var/www, for example, you can deploy with an Apache virtual host configuration like this:


<VirtualHost *:80>
    ServerName www.example.com
    ServerAdmin webmaster@example.com

    Alias /static/ /var/www/KillerApp/root/static/

    FastCgiServer /var/www/KillerApp/script/killerapp_fastcgi.pl \
        -processes 5 

    Alias / /var/www/KillerApp/script/killerapp_fastcgi.pl/

    ErrorLog /var/www/logs/error_log
    CustomLog /var/www/logs/access_log combined

</VirtualHost>

FastCGI is a proven, language-independent interface for running Web applications. It is essentially just plain CGI, but it keeps programs running in the background instead of firing them up for every request. This is the major limitation of CGI that FastCGI overcomes. FastCGI has been around for a long time. The use of this efficient protocol is another example of how Catalyst leverages existing solutions.

FastCGI allows you to specify the number of processes to run (five in the example above), making your application multithreaded. Incoming requests are distributed evenly among the processes, which are maintained in a pool.

The alias for <code>/static/</code> above tells Apache to serve the files directly in this directory (images, CSS, JavaScript files and so on). This is more efficient than serving these files through the application, which isn't necessary.

Conclusion

This article is meant to provide only a taste of Catalyst and its capabilities. As I hope you have seen, Catalyst is a viable platform for any Web development project. With a flexible design and many available mature features, you can use Catalyst to build robust applications quickly and conveniently.

Catalyst is actively developed and is getting better all the time, including its ever-increasing quality documentation. It also has a very active user community with top experts available via IRC.

When you're ready to start writing an application, you should be able to find the information and support you need to hit the ground running. See the Resources for this article for important links and where to get started.

Resources

Catalyst Home Page: http://www.catalystframework.org

Catalyst::Manual: http://search.cpan.org/perldoc?Catalyst::Manual

Template Toolkit Home Page: http://www.template-toolkit.org

DBIx::Class::Manual: http://search.cpan.org/perldoc?DBIx::Class::Manual

Catalyst IRC Channel: #catalyst on http://irc.perl.org

"Moose" by Henry Van Styn, LJ, September 2011: http://www.linuxjournal.com/content/moose

The Definitive Guide to Catalyst (c) 2009 ISBN: 978-1-4302-2365-8 (print) and 978-1-4302-2366-5 (on-line).

______________________

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Error in template?

j0e's picture

In page 3 of this article:

$c->stash->{data}->{title} = 'TT rendered page';

Shouldn't the template have this:

[% data.title %]

Instead of what is in the article:

[% title %]

This was an effective review for me, thank you!

[% data.message %] too

j0e's picture

I should have also mentioned that given:

$c->stash->{data}->{message} = 'A cool message!';

The following in the template:

[% message %]

needs to be:

[% data.message %]

Good work

Mas BlackBerry's picture

I like post a complete catalyst tutorial, i want to know if reference for it article, tks

Really nice article! Catalyst

Anonymous's picture

Really nice article! Catalyst is great framework with great community behind it

typo

Jon Bjornstad's picture

In this text:

The alias for /static/ above tells Apache to serve the files directly in this directory (images, CSS, JavaScript files and so on). This is more efficient than serving these files through the application, which isn't necessary.

The <code> and </code> HTML tags surrounding /static/ somehow got through.

Good Job!

daniel.cristian's picture

Nice work! I hope you'll continue with another MVC framework from Perl, a more lighter one, Perl Dancer.

Daniel

Excellent!

Dominic's picture

With so many people still thinking of perl as "that legacy language that you run from the cgi-bin directory", it's good to see the modern stuff get some coverage. Nice one!

Good work, looking for more!

Chankey Pathak's picture

Only LinuxJournal could have come up with such article. Good work!

Try to post a complete catalyst tutorial, there's only one single tutorial available (CPAN's tutorial for catalyst, the best one).

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState