A Database-Driven Web Application in 18 Lines of Code

From zero to Web-based database application in eight easy steps.
Step 6: Set Up Your Application

With the database ready and Maypole installed, it's time to configure the application. A directive needs to be added into the Apache httpd.conf configuration file to set up a mod_perl handler for the Maypole application. I added the following to the end of the configuration file:


<Location /Club>
    SetHandler perl-script
    PerlHandler ClubDB
</Location>

These lines tell Apache that when a request is made for the /Club URL, it is to be handed off to the ClubDB Perl script, which we write in the next step. Use the following commands, as root, to set up the URL location:

mkdir /var/www/html/Club
cd /var/www/html/Club
cp -r ~/.cpan/build/Maypole-2.04/templates/* .
cp maypole.css ../club.css

Having first created a directory to contain my application's URL underneath Apache's root directory, I then copied the default templates that ship with Maypole into this location. I also copied Maypole's CSS file into my Web server's DocumentRoot, giving it a name that corresponds to my application.

One final setup activity involves creating a configuration file within Apache's /etc/httpd/conf directory to hold the application's MySQL user ID and password. Called ClubDB.conf, this file contains these lines:

[client]
user=manager
password=passwordhere

Step 7: Write Your 18 Lines of Code

The code for the Soccer Club Database resides in the ClubDB.pm file. Every Maypole application starts with a package statement declaring a Perl namespace. Strictness is turned on, then the base Maypole module, called Apache::MVC, is used:

package ClubDB;

use strict;

use base 'Apache::MVC';

The code then establishes a connection to the database, using the user ID and password from the named configuration file:

ClubDB->setup( "dbi:mysql:CLUB;
    mysql_read_default_file=
        /etc/httpd/conf/ClubDB.conf" );

A few more lines of code inform Maypole of the base Web address for the application, as well as a list of tables in the database to which to provide access. For this simple application, it makes sense to provide access to all the tables:

ClubDB->config->{uri_base} =
    "http://webmason.itcarlow.ie/Club/";

ClubDB->config->{display_tables} =
    [ qw[ player squad condition ] ];

When it comes to squads, my application allows the user to view, edit or delete squad names. Specifying this takes a couple of lines of code, one of which sets up another namespace:

package ClubDB::Squad;

sub display_columns{ "name" };

ClubDB::Player->untaint_columns(
    printable => [ "name" ] );

The untaint_columns method identifies the type of data expected in the column, as well as indicates to Maypole that the column can be edited using the Web interface. Medical conditions are handled in the same way:

package ClubDB::Condition;

sub display_columns{ "name" };

ClubDB::Condition->untaint_columns(
    printable => [ "name" ] );

The code for the player table is more complex but not by much. After declaring another namespace, two calls to the has_a method establish the links between the player table and the others. The link is specified in terms of only the declared namespaces:

package ClubDB::Player;

ClubDB::Player->has_a(
    squad => "ClubDB::Squad" );

ClubDB::Player->has_a(
    medical_condition => "ClubDB::Condition" );

For players, we list the columns to display using the display_columns method. Doing so allows the programmer to control the order in which the columns appear within the Web interface. If display_columns is not used, Maypole displays the columns in alphabetical order, which may not always suit your needs. The invocation of untaint_columns identifies the types of data that can be edited within each of the columns. The code concludes with Perl's familiar 1;, which is required of all Perl modules:

sub display_columns{ qw( name address
    date_of_birth contact_tel_no
        squad medical_condition ) };

ClubDB::Player->untaint_columns(
    integer   =>
        [ "squad", "medical_condition" ],
    printable =>
        [ "name", "address", "contact_tel_no" ],
    date      =>
        [ "date_of_birth" ] );

1;

Count the semicolons. Bearing in mind that the presented code has been formatted to fit the printed page, there are only 18 lines of code in all. All that's left to do is copy the Perl module into a location where Apache and mod_perl can find it:

mkdir -p /etc/httpd/lib/perl/
cp ClubDB.pm /etc/httpd/lib/perl/

______________________

Comments

Comment viewing options

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

Please help

Justin Rickert's picture

I have tried to get the content of this article to work for three days now. I have finally got all the modules from CPAN installed. However when I try and use the App I get this message in the httpd error log:

failed to resolve handler `ClubDB':

and

Can't locate loadable object for module Apache::Constants

I installed Apache::Constants with
# perl -MCPAN -eshell
# install Apache::Constants

I have followed this article content and dont understant why it don't work.

Fights with Apache

Jason McKenna's picture

I'm running SuSE 9.1 with Apache 2 and had a hard time fighting to get things working. The one thing which took me the longest time to figure out was the Apache::MVC module does a check to see if you're running Apache 1 or 2. If 2 it requires one set of libraries, if 1 then a different set.

They both require Apache::Request, but as far I've been able to determine, this is not available for Apache 2:

if (APACHE2) {
require Apache2;
...
} else { require Apache }
require Apache::Request;

I seem to have fixed the problem by putting the "require Apache::Request" line inside the else block.

I don't know Perl or the Apache modules enough to say if this is a bug in MVC, or if my system is grossly misconfigured. Regardless, Maypole is working for me now, but I'm continuing to research. Any ideas?

Thanks!

Can't compile libapreq2 either

scottebetts's picture

Even though /sbin is in my path already. I'm on FC3 that was upgraded from FC2. I may try a clean new install in order to give this a whirl.

I couldn't get this tutorial

ElaineNormandy's picture

I couldn't get this tutorial to work until I made the following changes:

1. include /sbin in path when compiling libapreq2 module.

2. changed ClubDB.pm to have the following line:

ClubDB->setup( "dbi:mysql:CLUB", "manager", "passwordhere" );

instead of existing ClubDB->setup line.

Hope these tips help someone else save some hours.

Getting it to work

Mitch Kuppinger's picture

In addition to ElaineNormandy's suggestion which was key to getting this to work, I can offer these suggestions:

In ClubDB.pm since at line 9 we are in the ClubDB::Squad package definition, line 9 should be changed from "ClubDB::Player->untaint..." to "ClubDB::Squad->untaint...".

Be VERY carefull with your syntax in ClubDB.pm. For example, using curved braces, '(' and ')', instead of curly braces, '{' abd '}', after 'sub display_columns' causes the display of the associated table to be replaced by a message that the page can't be opened. The log ( logs/error.log) is minimally helpfull with this.

Be sure to restart Apache whenever ClubDB.pm is changed.

Paul Barry's article is thorough but does not walk you thru installing and setting up Apache and mod_perl, if you don't have them. This has to be done right to get the rest to work. Having the source code and all the resultant files from the build process (eg. apxs ) appears to be necessary to install libapreq2. My initial install of fc3 did not have these. It took a bit of poking around to get these required files in place.

All that said, I now have the tools in place to move some very usefull Interbase SQL databases to mysql and serve them up with browser technology to the various offices in our organization. Thanks to Paul Barry, Simon Cozens and Sebastion Riedel.

Getting it to work ... more

barryp's picture

Paul Barry's article is thorough but does not walk you thru installing and setting up Apache and mod_perl, if you don't have them.

I initially had a version of the article that covered installing Apache/mod_perl from source. However, in discussions with LJ's editor, it was decided that the article would be more useful if I targetted a distribution's build of Apache/mod_perl, the thinking being that if a distribution issued a security fix, it could be applied to the system as a result of the distribution's updating system. The idea was that building from source would mean that the user would then be taking on responsibility for updating Apache/mod_perl when security patches were issued. It was felt that people are busy enough, so we stuck with a distribution's Apache/mod_perl package.

My initial install of fc3 did not have these. It took a bit of poking around to get these required files in place.

As the last step of Part 1, I state: "be sure to install the following packages from your chosen distribution: httpd, httpd-devel, mod_perl, mod_perl-devel, mysql (client and server) and Perl.". With these packages installed, APXS and the like are installed for you. I did this on FC3 with no real issues.

Interbase SQL

You may wish to try hooking Maypole up to Interbase and avoid the step of moving your data to MySQL. Maypole is database-independent. Worth checking out.

Thanks to Paul Barry, Simon Cozens and Sebastion Riedel.

Oh my ... all I did was write the article. The "Simons" did all the real work and they deserve all the credit.

Thanks for the comments on the article. Glad you found it useful.

Regards.

Paul.

Paul Barry

getting Maypole (this tutorial) to work

barryp's picture

Unfortunately (or fortunately, depending on how you view things) Maypole and its API is constantly under development. The module is now at release 2.09, whereas my code worked under 2.04 and that was just a few short months ago. The best advice I can give web developers is to subscribe to the Mayole mailing list and to check any list archives. And -- yes -- getting Maypole to work is a challenge but, once it works, I think its worth the heartache.

Paul Barry

Paul Barry

Just the thing I've been pull

Anonymous's picture

Just the thing I've been pulling my hair out over the last 20 mins. Thanks!

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