Embperl - building dynamic websites with Perl


Modular Files
[ << Prev: Website-Global Variables ] [ Content ] [ Next: Modular File Inheritance >> ]

The previous example is nice, it demonstrates the basic ability to have website-wide variables set up in base.epl and then automatically shared by all other files. Leading on from this, we probably want to split up our files, for both maintainability and readability. For example, a non-trivial website will probably define some website-wide constants, perhaps some global variables, and maybe also have some kind of initialization code which has to be executed for every page (e.g. setting up a database connection). We could put all of this in base.epl, but this file would quickly begin to look really messy. It would be nice to split this stuff out into other files. For example:

/base.epl

   	<HTML>
	[- Execute ('constants.epl')-]
	[- Execute ('init.epl')-]
   	<HEAD>
		<TITLE>Some title</TITLE>
	</HEAD>
	<BODY>
	[- Execute ('*') -]
	</BODY>
	[- Execute ('cleanup.epl') -]
	</HTML>

/constants.epl

[- $req = shift; $req->{bgcolor} = "white"; $req->{webmaster} = "John Smith"; $req->{website_database} = "mydatabase"; -]

/init.epl

[- $req = shift; # Set up database connection use DBI; use CGI qw(:standard); $dsn = "DBI:mysql:$req->{website_database}"; $req->{dbh} = DBI->connect ($dsn); -]

/cleanup.epl

[- $req = shift; # Close down database connection $req->{dbh}->disconnect(); -]

You can see how this would be useful, since every page on your site now has available a database connection, in $req->{dbh}. Also notice that we have a cleanup.epl file which is always executed at the end - this is very useful for cleaning up, shutting down connections and so on.


[ << Prev: Website-Global Variables ] [ Content ] [ Next: Modular File Inheritance >> ]


© 1997-2023 Gerald Richter / actevy