Mojolicious Utilities

Introducing Mojolicious's utilities.

Inheritance

If you want to inherit, you can do it in the base module, but Mojolicious provides a slightly enhanced inheritance method. To perform extended inheritance, use the import function of Mojo::Base.

package MyApp::Photoshoot;
use Mojo::Base'Mojolicious::Controller';

The above description is an example of creating the MyApp::Photoshoot class by inheriting the Mojolicious::Controller class.

The Mojo::Base inheritance feature provides additional functionality such as:

  • Automatically perform "use strict"
  • Automatically perform "use warnings"
  • Has method that defines the attribute is imported

Define an accessor

To define an accessor, use the attr method of the Mojo::Base class, or use the has function imported by the Mojo::Base inheritance feature. You can also set default values ​​for the accessors.

In the case of Mojolicious::Lite, you can add attributes to the application class by calling the attr method from the application object.

#Mojolicious::Lite
app->attr(x => 1);

# Accessor
my $x = app->x;
app->x(3);

For Mojolicious, use the has function imported into Mojo::Base by the inheritance feature.

#Mojolciious

has x => 1;

sub startup {
    my $self = shift;
    
    # Accessor
    my $x = $self->x;
    $self->x(3);
}

Notes on default values ​​

If the default value is non-constant, such as a number and a string, it should be given as the return value of the subroutine reference. This is what you need to avoid sharing values ​​with other objects.

app->attr(nums => sub {[1, 2, 3]});
app->attr(person => sub {{name =>'Ken', age => 19}});
app->attr(dbh => sub {DBI->connect(...)});

Get and set the mode

Use the mode method of the Mojolicious class to get and set the mode.

#How to use
my $mode = $app->mode;
$app->mode('test');

#Mojolicious::Lite
app->mode;

#Mojolicious (from Controller)
$self->app->mode;

The default mode is development. When you run the application with hypnotoad, the mode will be production.

You can also set the mode using environment variables.

export MOJO_MODE = test

Application class description

I will explain the class that represents the main body of the Web application. In the explanation from here, the class that represents the Web application itself will be called the application class.

Application class

Let's take a look at the source code to understand the application classes. The application name is Sampleapp.

package Sample app;
use Mojo::Base'Mojolicious';

#This method will run once at server start
sub startup {
  my $self = shift;

  #Routes
  my $r = $self->routes;
  $r->get('/')->to('main # default');
}

1;

The first thing to notice is the next part. You can use Mojo::Base to inherit classes.

use Mojo::Base'Mojolicious';

The application class is created by inheriting a class called Mojolicious. This means that you can use all the methods defined in Mojolicious in Sampleapp.

Also, since Mojolicious inherits Mojo, Sampleapp can use all the methods defined in Mojo.

Application settings startup

A method called startup is defined in Sampleapp. This method is called only once when the application is initialized. Therefore, the settings related to the application will be made in this method. You will write the definition of dispatch etc. in the startup method.

sub startup {
  my $self = shift;

  #Routes
  my $r = $self->routes;
  $r->get('/')->to('main # default');
}

Methods often used in application classes

Sampleapp inherits from Mojolicious, and Mojolicious inherits from Mojo, so you can use those methods. Here are some of the most commonly used methods.

log --Getting the logger

Mojolicious has a function to output logs according to the setting level. That functionality is implemented in the class " Mojo::Log".

The application class has a Mojo::Log object and can be retrieved with the "log" method. In the startup method, $self is an object that represents the application, so you can call log from here.

sub startup {
  my $self = shift;

  #Getting a logger
  my $log = $self->log;
    
  # Output to log at debug level
  $log->debug('message');
}

home --Get home object

Mojoliciou has a class called "Mojo::Home" that represents the home directory of the application. Use the "home" method to get this object.

sub startup {
  my $self = shift;

  #Get home object
  my $home = $self->home;
}

Read the configuration file

Use Mojolicious::Plugin::Config to read the configuration file. Below is a sample that loads myapp.conf in the application's home directory.

#Mojolicious Lite
my $conf = plugin ('Config', {file => $self->app->home->rel_file('myapp.conf')});

#Mojolicious
my $conf = $self->plugin(
  'Config',
  {file => $self->app->home->rel_file('myapp.conf')}
);

Below is a sample configuration file. You can write database information etc. in the configuration file.

{
  db_dsn => "DBI: mysql: database = bookshop;",
  db_user => "ken",
  db_password => "FJ5klsd%&"
}

Customize the configuration file according to the mode

Mojolicious allows you to customize the contents of the configuration file according to the mode. The setting according to the mode is

myapp.production.conf

like

Configuration file name.mode name.extension

Write it in the file named.

For example, to customize the database password for production, overwrite the value of db_password as follows:

# myapp.production.conf
{
  db_password => "change !!!!"
}

Read two configuration files

Sometimes you may want to separate the config files and read the two config files. In that case, you can simply use the Config plugin twice. If the hash keys are the same, the settings will be overwritten.

$app->plugin(Config => {file => $conf_file1});
$app->plugin(Config => {file => $conf_file2});

Log generation management

When Mojolicious is operated with hypnotoad in the production environment, a log called production.log will be gradually accumulated.

If you are using CentOS, it is easy to use logrotate to manage logs. Place the logrotate configuration file in the directory where your application is located. This time, suppose you have a webapp directory under your home directory.

cd webapp
mkdir logrotate
cd logrotate
vi logrotate.conf

Describe the configuration file as follows. It is set to copy and rotate the log file once a week.

/home/ken/webapp/log/production.log {
  weekly
  copytruncate
  rotate 12
  missingok
}

After that, let's register the command that actually executes the rotation in crontab.

crontab -e

Describe the following contents.

0 0 * * * / usr / sbin / logrotate -s $HOME / webapp / logrotate / logrotate.status $HOME / webapp / logrotate / logrotate.conf

Change the browser shortcut icon (favicon)

By default, Mojolicious displays a cloud-marked favicon, but it's easy to change.

Just place it under the public directory with the name favicon.ico .

public
  --favicon.ico

The old favicon is cached in your browser, so you may need to clear your browser's cache when checking.

If you want to set up a favicon by specifying a file name, specify shortcut icon for rel in the HTML link tag and do as follows. A favicon is installed under the public directory with the name example.ico .

use Mojolicious::Lite;

get'/' =>'index';

app->start;

__DATA__

@@index.html.ep
<html>
  <head>
    <link rel = "shortcut icon" href = "<%= url_for'/example.ico'%>">
    <title> Favicon Example </title>
  </head>
  <body>
    Favicon Example
  </body>
</html>

How to use Mojolicious with Perl 5.8.7

Version 5 of Cent OS is still widely used and I think it will take a long time to move to the new version. The Perl version is sadly 5.8.7. And the good news is that I have a project to backport Mojolicious so that it can run in Perl 5.8.7.

With this, you can write highly portable web applications using Mojolicious.

Check the log

When developing with Mojolicious, there are times when you want to see what kind of error is occurring, such as when the source code is incorrect. In such a case, let's check the log.

If the log directory is in the same directory as the script, the log will be output to that directory, otherwise the content will be output to the standard error output.

It is usually convenient to create a log directory.

For #Mojolicious::Lite
myapp.pl
log /
For #Mojolicious
script / myapp
log /

Log name

The log is output to the log directory, but the log name has the following rules:

Mode name.log

For example, if you are running your application in development mode using morbo, the log name will be development.log. .. This is because the default mode when running with morbo is development.

log / development.log

Also, when running with hypnotoad in a production environment , the log name will be production.log. This is because production is set by default as the mode name when running with hypnotoad.

log / production.log

Use the mode method (Mojolicious class) to change the mode.

#Mojolicious::Lite example
app->mode('test');

# Mojolicious example
sub startup {
  my $self = shift;
  $self->mode('test');
}

A convenient way to check logs on Unix / Linux

On Unix / Linux, it is convenient to use the tail command to check the logs. When a new log is output, its contents are automatically displayed.

tail -f log / development.log

Dump data dumper

When writing a web application, you often want to dump the data. In Mojolicious, you can simply do a die to call the exception class template and dump the data.

Using dumper , it looks like this:

die dumper $data;

Get a remote IP address

To get the remote IP address, use the remote_address method of Mojo::Transaction. This gets the corresponding remote host (REMOTE_ADDR) in the CGI environment variables.

#Get remote IP address
$c->tx->remote_address;

Get the Mojo::Transaction object from the controller object with the tx method and then call the remote_address method to get the remote IP address.

Get user agent (HTTP header User-Agent)

To get the accessing user agent (User-Agent), use the user_agent method of Mojo::Header.

#Get user agent header
$c->req->headers->user_agent;

Get the Mojo::Request object from the controller object with the req method, get the Mojo::Header object with the headers method, and then the user_agent method. call.

Check if the connection is secure from https

To find out if the connection is a secure connection from https , use the is_secure method of the Mojo::Message::Request class. increase.

my $secure = $req->is_secure;

Associated Information