Team LiB   Previous Section   Next Section

6.2 Mason

Jonathan Swartz, aided and abetted by Dave Rolsky, has created another fine Perl templating package in HTML::Mason. Unlike Embperl, which has a C-based back end, Mason is built purely with Perl, and this implementation tends to reduce potential complexities during installation.

You can download the latest package from CPAN and learn much more about Mason at the following sites:

http://www.masonhq.com
http://www.cpan.org/authors/id/J/JS/JSWARTZ

The following sections describe how to install Mason on Unix and Win32 and then work through an example.

6.2.1 Installing Mason on Unix

We need to pre-install the following Perl modules for Mason on Unix platforms:

Time::HiRes

Douglas E. Wegscheid's module helps Mason deal with POSIX commands such as usleep( ) and ualarm( ) at subsecond levels.

http://www.cpan.org/authors/id/DEWEG

MLDBM

Gurusamy Sarathy's Multi-Level DBM module serializes multilevel hashes, and all the data their references point to, into single BLOBs of data; these can then be stored by any one of the different Perl modules listed here. You can learn more at:

http://www.cpan.org/authors/id/GSAR

Data::Dumper

This comes automatically with Perl now, and saves Perl hash structures in neatly formatted platform-independent files, useful for printing or evaluating.

FreezeThaw

Converts Perl data structures to and from strings suitable for storage.

http://www.cpan.org/authors/id/ILYAZ/modules

Storable

As discussed earlier with Embperl, this module uses a C back end to greatly speed information storage and retrieval and thus make your Perl data structures persistent. We recommend that you load Storable, because it is significantly faster than either Data::Dumper or FreezeThaw.

http://www.cpan.org/authors/id/A/AM/AMS

Params::Validate

This validates method or function call parameters, and can also determine their type and class hierarchy relationships.

http://www.cpan.org/authors/id/D/DR/DROLSKY

Now follow these steps:

  1. Once the main modules above are installed, we can get to the main event:

    $ gzip -d HTML-Mason-1.04.tar.gz
    $ tar xvf HTML-Mason-1.04.tar
    $ cd HTML-Mason-1.04
  2. You may wish to set an environmental variable, APACHE, to direct the Mason configuration to pick up an Apache server with mod_perl attached[3] — for example:

    [3] As with Embperl, Mason can be operated without mod_perl, but you will achieve much better performance if you do use it.

    $ export APACHE=/usr/local/apache/bin/httpd
  3. Alternatively, just insert the full httpd file path when Makefile.PL asks for it:

    $ perl Makefile.PL
    ...
  4. For testing purposes, specify the full path to an httpd with mod_perl enabled. The path defaults to $ENV{APACHE}, if present.

     [/usr/local/apache/bin/httpd] ('!' to skip): 
    ...
    $
  5. Mason's make test step will also keep stopping and restarting httpd — for example:

    $ make
    $ make test
    ...
    Testing whether Apache can be started
    Waiting for httpd to start.
    Killing httpd process (746)
    Waiting for previous httpd to shut down
    ...
    $ make install

6.2.2 Installing Mason on Win32

To install Mason on Win32 platforms, simply connect to the Internet, call up PPM, and install HTML::Mason direct from the University of Winnipeg. (You'll notice on the actual install that you'll get a lot of other modules delivered.)

PPM> set repository theoryx5 
     http://theoryx5.uwinnipeg.ca/cgi-bin/ppmserver.pl?urn:/PPMServer
PPM> install HTML-Mason
Install package 'HTML-Mason?' (y/N): y
Installing package 'HTML-Mason'...
...

You then can install the following additional modules from the ActiveState site:

PPM> install Time-HiRes
Install package 'Time-HiRes?' (y/N): y
Installing package 'Time-HiRes'...
...
PPM> install MLDBM
Install package 'MLDBM?' (y/N): y
Installing package 'MLDBM'...
...
PPM> quit
6.2.2.1 Installing Params::Validate

There is a slight complication with Mason on Win32: it requires the Params::Validate module. This module may not be available from either the University of Winnipeg, which specializes in difficult-to-install XS modules, or ActiveState itself. Fear not, for HTML::Mason is a pure Perl module, so in the worst case we can create our own PPM installation with it very easily. Here's how:

  1. First, get the latest tarball from Dave Rolsky's site:

    http://www.cpan.org/authors/id/D/DR/DROLSKY
  2. Unpack it to its own directory, using gzip or WinZip. Go to this directory and run the following command:

    C: \Params-Validate-0.14>perl Makefile.PL
  3. Now, while steadying your hand with a single malt whisky, download the latest NMAKE self-inflating program from Microsoft into the C: \Params-Validate-0.14 directory. The latest incarnation of NMAKE should always be pointed to by the current ActiveState PPM FAQ. The one we used was:

    http://aspn.activestate.com/ASPN/PPM/FAQ

    This pointed us towards the NMAKE download at the following address:

    http://download.microsoft.com/download/vc15/Patch/1.52/W95/EN-US/Nmake15.exe
  4. Once you've got this, inflate it:

    C: \Params-Validate-0.14>Nmake15.exe
    ...
      Inflating: NMAKE.ERR
      Inflating: NMAKE.EXE
      Inflating: README.TXT
  5. Now run the NMAKE.EXE program, which will read the Makefile created earlier by the perl Makefile.PL step:

    C: \Params-Validate-0.14>nmake
    ...
    cp lib/Attribute/Params/Validate.pm blib\lib\Attribute\
          Params\Validate.pm
    cp lib/Params/Validate.pm blib\lib\Params\Validate.pm
  6. You can even run tests if you want to:

    C: \Params-Validate-0.14>nmake test
    ...
    noop.t t\03-attribute.t t\04-defaults.t t\05-noop_default.t
    Using C:/Params-Validate-0.14/blib
    t\01-validate.......ok
    t\02-noop...........ok
    ...
  7. We're now ready to install Params::Validate via the PPM program:

    C: \Params-Validate-0.14>ppm install
    ...
    Installing C:\Perl\site\lib\Attribute\Params\Validate.pm
    Installing C:\Perl\site\lib\Params\Validate.pm
    Writing C:\Perl\site\lib\auto\Params\Validate\.packlist
    C: \Params-Validate-0.14>

    Mason is now ready for launch on Win32.

6.2.3 Configuring Mason for Apache

There is plenty of excellent documentation on configuring Mason for use with Apache. Simply point your browser at the HTML documents that come with the Mason download:

../htdocs/index.html

To configure Mason, visit the following page:

../htdocs/Mason.html#configuring_mason

In this section, we'll illustrate a fairly simple setup — we'll treat all the files found with the .mcomp suffix as special Mason templates files. We added the following to our httpd.conf file, including two alternative commented-out lines for Win32:

PerlSetVar MasonCompRoot /usr/local/apache/htdocs
PerlSetVar MasonDataDir /usr/local/apache/mason
#PerlSetVar MasonCompRoot "C:/Program Files/Apache Group/Apache/htdocs"
#PerlSetVar MasonDataDir "C:/Program Files/Apache Group/Apache/mason"
PerlModule HTML::Mason::ApacheHandler
<FilesMatch "*.mcomp">
   SetHandler perl-script
   PerlHandler HTML::Mason::ApacheHandler
</FilesMatch>
AddType text/html .mcomp

Let's see what's going on here:

  1. The MasonCompRoot directive tells Apache where our Mason component root will be (in this case, it's the same as our default document root).

  2. The MasonDataDir directive tells Apache where Mason will be storing transitory and permanent data information. Although this directory and its subdirectories will be created automatically on server startup, we'll take the trouble to create the Mason directory manually here just to show how it's done:

    $ cd /usr/local/apache
    $ mkdir mason
  3. The PerlModule directive assigns Mason the requisite Apache handler.

  4. The FilesMatch block next tells Apache to look out for .mcomp files and to direct them toward Mason's Apache handler, if it should find them.

  5. We also need to let Apache know that .mcomp files are to be ultimately treated as .html files, with the AddType line.

Now that we've loaded Mason, let's take a look at using it. Like Embperl, Mason is component-based, a mixture of Perl and HTML that gives you powerful direct access into the heart of the Apache server. We've briefly summarized its major features in Table 6-2.

Table 6-2. Mason's main object features

Mason API

Description

Request

Provides a gateway to all of Mason's extra features beyond syntactic tags

Component

Allows you to examine components currently loaded into memory

Parser

Translates components into Perl subroutines

Interpreter

Defines how Mason components are loaded and then executed

ApacheHandler

Connects Mason to mod_perl, in response to HTTP requests

Next, we'll work through Mason's inline use of Perl (here's where it comes closest in functionality to Embperl). The three inline methods are all used in Example 6-2, which is executed and displayed in Figure 6-2.

Example 6-2. hello.mcomp
<html><head><title>Hello HTML::Mason</title></head><body>
<center>
  
<p><h1>HTML::Mason :-)</h1><hr>
  
<%perl>
my $noun = 'World';
my @time = split /[\s:]/, localtime;
</%perl>
  
<h2>Hello <% $noun %>,
% if ( $time[4] < 12 ) {
   Good morning.
% } elsif ( $time[4] < 18 ) {
   Good afternoon.
% } else {
   Good evening.
% }
</h2><br>
<h3><% scalar(localtime) %></h3>
  
<hr></center></body></html>
Figure 6-2. Hello Mason!
figs/pdba_0602.gif

Table 6-3 provides examples of the three types of inline Perl available with Mason.

Table 6-3. Embedding Perl within the Mason template

Format

Description

Example

<% ... %>

The single piece of Perl within the braces is evaluated and returned to the browser.

Hello, <% $user_login %>!

% ...

Any line beginning with % is treated as a Perl line to be executed.

% if ( /Hello/ ) {

<%perl> ...

</%perl>

For code blocks, use this syntax, and everything between the tags is executed as Perl code. The tag is case-insensitive so <%PERL> ... </%PERL> is equally valid.

<%perl>

my $dbh = DBI->connect( $url, $user, $passwd );

</%perl>

For a database-related example, we've provided MasonBlock.mcomp in Example 6-3. Once again, set mod_perl running, along with the target database, and call up the page as in Figure 6-3.

Incidentally, one of the things we especially like about Mason is the comprehensive error browser reporting it provides. This feature greatly aids the development of code, especially when it's all spaghettified across the httpd server, mod_perl, Perl itself, and the Oracle database!

Example 6-3. MasonBlock.mcomp — Combining Mason with DBI
<html><head><title>Hello HTML::Mason and DBI</title></head><body>
<center>
<p><h1>Chiseling into DBI with HTML::Mason 8)</h1><hr>
  
<%perl>
  
use DBI;
  
my $url = 'dbi:Oracle:orcl';
my $user = 'system';
my $passwd = 'manager';
  
my $dbh = DBI->connect($url, $user, $passwd, {RaiseError=>1});
  
my $sth = $dbh->prepare(
   'select tablespace_name tabSpace, ' .
          'segment_type segType, ' .
          'owner, ' .
          'segment_name segName, ' .
          'blocks, ' .
          'bytes, ' .
          'extents, ' .
          'next_extent nextExt ' .
     'from dba_segments ' .
    'where owner != \'SYS\' ' .
    'order by 1, 2, 3, 4');
  
$sth->execute;
my $rs = $sth->{NAME};
  
</%perl>
  
<table border="2">
<tr>
% for my $heading (@$rs)
% {
      <th><% $heading %></th>
% }
</tr>
  
% while (my @row = $sth->fetchrow_array)
% {
<tr>
%    for my $data (@row)
%    {
         <td><% $data %></td>
%    }
</tr>
% }
<caption>DBA Segments</caption></table>
  
% $dbh->disconnect;
  
<hr></center></body></html>
Figure 6-3. Mason, Oracle, and DBI
figs/pdba_0603.gif

If you still hunger for more Perl HTML templating, you may to try out Sam Tregar's HTML::Template module. This module is based on the use of extended HTML tags. HTML::Template aims for a more lightweight, streamlined interface than those offered by Embperl and Mason, while also stressing the separation of design and content production. You may also be tempted by the larger solutions of Andy Wardley's Template Toolkit or Matt Sergeant's XML-based AxKit (you'll find more on XML in Appendix D). Check out the following:

http://www.cpan.org/authors/id/S/SA/SAMTREGAR
http://www.cpan.org/authors/id/ABW
http://www.openinteract.org
http://openinteract.sourceforge.net
http://www.cpan.org/authors/id/M/MS/MSERGEANT
http://perl.apache.org/features/tmpl-cmp.html
    Team LiB   Previous Section   Next Section