Catalyst MVC Framework Fundamentals

Preface
There are very few Habrés, or rather there are absolutely no articles about such a wonderful MVC framework as Catalyst. And so I decided to devote my first article to him.
Here I described the basic principles for working with Catalyst using a simple web application as an example, the so-called quick start to learn this framework.

Introduction
Catalyst is a powerful MVC framework for developing web applications in Perl.
A few words about MVC (Model / View / Controller):
  • Model (Model) - contains only data and methods for working with them.
  • View (View) - is responsible for how exactly this data will look.
  • Controller (Controller) - controls the communication between the system and the user, and also controls the necessary interactions during the application.

Catalyst - contains an extensive number of CPAN modules that facilitate the development of a Perl web application.

What is the simplicity of using this framework?


The process of creating a new project is carried out using the command: catalyst.pl Test::App (in the file system in the directory with the project name “::” it will be replaced by “-”.

This script is part of an auxiliary system called Catalyst :: Helper, which generates the necessary scripts, folders, tests, files, etc. for the future application.

Structure of the created project:
  • / lib - the heart of the project, contains all the perl code intended for the web application, consists of subdirectories created automatically:
    1. Test / App / Model - for modules implementing the model;
    2. Test / App / View - ... view;
    3. Test / App / Controller - ... controller;
    4. Test / App / App.pm - module for setting up a web application.

  • / root - templates for View are stored here, necessary css, js, images, in general, all static data;
  • / script - contains scripts that were automatically created by Helper. They are necessary to run:
    1. test server;
    2. testing a specific URL;
    3. creating MVC components;
    4. running scripts like CGI / FastCGI;
    5. etc.

  • / t - contains tests
  • Changes - the history of changes to your project.
  • Makefile.PL - service info for installing the necessary modules when deploying the application.
  • test_app.conf - configuration file, utility variables are specified (has the highest priority at startup than the settings inside the application).
  • README - information about the launch of the application, its installation, settings, etc.

Adding the necessary models / views / controllers is performed using the appropriate command: The script/test_app_create.pl {model|view|controller} {имя компонента}

contents of the TestApp.pm file

package Test::App;
use Moose;
use namespace::autoclean;
use Catalyst::Runtime 5.80;
use Catalyst qw/
    -Debug # включает режим отладки
    ConfigLoader # возможность настройки приложения
    Static::Simple # обслуживание статических файлов из /root
/;
extends 'Catalyst';
our $VERSION = '0.01';
__PACKAGE__->config(
    name => 'Test::App',
    disable_component_resolution_regex_fallback => 1,
    enable_catalyst_header => 1, # Send X-Catalyst header
);
# стартует приложение
__PACKAGE__->setup();
1;

As we can see, Catalyst uses the Moose module for object display of the CPAN elements used, which greatly simplifies working with objects in the Perl language.

The Root.pm file located in the / lib / Test / App / Controller / folder looks like this:

# содержит методы необходимые для взаимодействия с приложением, обработки запросов и генерации ответов.
package Test::App::Controller::Root;
use Moose;
use namespace::autoclean;
BEGIN { extends 'Catalyst::Controller' }
__PACKAGE__->config(namespace => '');
# начальная страница, об этом говорит цифра Args(0), цифра внутри, указывает количество параметров в url (прим. test.com/1a/2b/3c при Args(1) получим "1b" и т.д)
sub index :Path :Args(0) {
    my ( $self, $c ) = @ _;
    # Hello World
    $c->response->body( $c->welcome_message );
}
# для всех остальных запросов, для которых не найдены соответствующие указания, генерирует ошибку 404
sub default :Path {
    my ( $self, $c ) = @ _;
    $c->response->body( 'Page not found' );
    $c->response->status(404);
}
# метод, выполняющийся в конце обработки запроса
sub end : ActionClass('RenderView') {}
1;


Now, after exploring this framework, let's try to create a simple web application.

1. Create a view using the command script/test_app_create.pl view Web TT(TT - Template Toolkit, template engine, you can also use other template engines, Mason for example)

2. Create an index.tt file in the root folder /
Insert this code there:
 [% IF result %]

[% result %]

[% END %]


3. In the Root.pm file, delete the following line: $c->response->body( $c->welcome_message ); # вывод стандартного окна приветствия

4. there we add the hello method:

sub hello :Local {
	my ($self, $c) = @ _;
	my $hi = $c->req->body_params->{hi};
	$c->stash(
		result => $c->model('Hello')->hello($hi),
		template => 'index.tt',
	);
}

5. Create a model 6. In the created model, write the method:script/test_app_create.pl Model Hello



sub hello {
	my ($self, $hi) = @ _;
	return "Hello $hi!\n";
}


7. Run the test server script/test_app_server

8. In the browser, enter localhost:3000/(default port)

We admire the result.

PS Here in principle the main ideas when working with Catalyst, and I would like more articles on the hub from people who know this framework, people. The documentation is certainly good, but the real experience is always more interesting.

PPS While writing this article, it could not do without the magic of pearl. The code uses the array "@_", which is translated in tags when specifying the pearl language in the habrayuzer with the name "_", nothing beautiful came up with how to put spaces between @ and _. Be careful…

Also popular now: