Perl Writing Library Files

Per l PERL5LIB Environm ent variable PHP include_path Configurat ion variable Pyt hon PYTHONPATH Environm ent variable Java CLASSPATH Environm ent variable I n each case, t he variable value is a direct ory or set of direct ories. For exam ple, if under Unix I put Perl library files in t he u paul lib perl direct ory, I can set t he PERL5LIB environm ent variable for t csh like t his in m y .login file: setenv PERL5LIB upaullibperl Under Windows, if I put Perl library files in D: \ lib\ perl, I can set PERL5LIB as follows in AUTOEXEC.BAT: SET PERL5LIB=D:\lib\perl I n each case, t he variable set t ing t ells Perl t o look in t he specified direct ory for library files, in addit ion t o what ever ot her direct ories it would search by default . The ot her environm ent variables PYTHONPATH and CLASSPATH are specified using t he sam e synt ax. For m ore inform at ion on set t ing environm ent variables, see Recipe 1.9 . For PHP, t he search pat h is defined by t he value of t he include_path variable in t he PHP init ializat ion file t ypically nam ed php.ini or php3.ini . On m y syst em , t he files pat hnam e is usr local lib php.ini; under Windows, t he file is likely t o be found in t he Windows syst em direct ory or under t he m ain PHP inst allat ion direct ory. The value of include_path is defined w it h a line like t his: include_path = value The value is specified using t he sam e synt ax as for environm ent variables t hat nam e direct ories. That is, it s a list of direct ory nam es, wit h t he nam es separat ed by colons under Unix and sem icolons under Windows. For exam ple, if you want PHP t o look for include files in t he current direct ory and in t he lib php direct ory under t he web server root direct ory usr local apache, include_path should be set like t his under Unix: include_path = .:usrlocalapachelibphp I f you m odify t he init ializat ion file and PHP is running as an Apache m odule, youll need t o rest art Apache t o m ake t he change t ake effect . Now let s const ruct a library for each API . Each sect ion here dem onst rat es how t o writ e t he library file it self, t hen discusses how t o use t he library from wit hin program s.

2.4.4 Perl

I n Perl, library files are called m odules, and t ypically have an ext ension of .pm Perl m odule . Heres a sam ple m odule file, Cookbook.pm , t hat im plem ent s a m odule nam ed Cookbook . I t s convent ional for t he basenam e of a Perl m odule file t o be t he sam e as t he ident ifier on t he package line in t he file. package Cookbook; Cookbook.pm - library file with utility routine for connecting to MySQL use strict; use DBI; Establish a connection to the cookbook database, returning a database handle. Dies with a message if the connection cannot be established. sub connect { my db_name = cookbook; my host_name = localhost; my user_name = cbuser; my password = cbpass; my dsn = DBI:mysql:host=host_name;database=db_name; return DBI-connect dsn, user_name, password, { PrintError = 0, RaiseError = 1}; } 1; return true The m odule encapsulat es t he code for est ablishing a connect ion t o t he MySQL server int o a funct ion connect , and t he package ident ifier est ablishes a Cookbook nam espace for t he m odule, so you invoke t he connect funct ion using t he m odule nam e: dbh = Cookbook::connect ; The final line of t he m odule file is a st at em ent t hat t rivially evaluat es t o t rue. This is needed because Perl assum es som et hing is wrong wit h a m odule and exit s aft er reading it if t he m odule doesnt ret urn a t rue value. Perl locat es m odule files by searching t hrough t he direct ories nam ed in it s INC array. This array cont ains a default list of direct ories. To find out what t hey are on your syst em , invoke Perl as follows at t he com m and line: perl -V The last part of t he out put from t he com m and shows t he direct ories list ed in t he INC array. I f you inst all a m odule file in one of t hose direct ories, your script s will find it aut om at ically. I f you inst all t he m odule som ewhere else, youll need t o t ell your script s where t o find it by including a use lib st at em ent . For exam ple, if you inst all t he Cookbook.pm m odule file in usr local apache lib perl, you can writ e a t est harness script harness.pl t hat uses t he m odule as follow s: usrbinperl -w harness.pl - test harness for Cookbook.pm library use strict; use lib qwusrlocalapachelibperl; use Cookbook; my dbh = Cookbook::connect ; print Connected\n; dbh-disconnect ; print Disconnected\n; exit 0; Not e t hat harness.pl does not have a use DBI st at em ent . I t s not necessary, because t he Cookbook m odule it self im port s t he DBI m odule, so any script t hat uses Cookbook also get s DBI . Anot her way t o specify where Perl should look for m odule files in addit ion t o t he direct ories t hat it searches by default is t o set t he PERL5LIB environm ent variable. I f you do t hat , t he advant age is t hat your script s wont need t he use lib st at em ent . The corresponding disadvant age is t hat every user who runs script s t hat use t he Cookbook m odule will have t o set PERL5LIB . 2.4.5 PHP PHP provides an include st at em ent t hat allows t he cont ent s of a file t o be read int o and included as part of t he current script . This provides a nat ural m echanism for creat ing libraries: put t he library code int o an include file, inst all it in one of t he direct ories in PHPs search pat h, and include it int o script s t hat need it . For exam ple, if you creat e an include file nam ed Cookbook.php, any script t hat needs it can use a st at em ent like t his: include Cookbook.php; The cont ent s of PHP include files are writ t en like regular script s. We can writ e such a file, Cookbook.php, t o cont ain a funct ion, cookbook_connect , as follow s: ?php Cookbook.php - library file with utility routine for connecting to MySQL Establish a connection to the cookbook database, returning a connection identifier. Dies with a message if the connection cannot be established. function cookbook_connect { db_name = cookbook; host_name = localhost; user_name = cbuser; password = cbpass; conn_id = mysql_connect host_name, user_name, password; if conn_id { If mysql_errno mysql_error work for failed connections, use them invoke with no argument. Otherwise, use php_errormsg. if mysql_errno { die sprintf Cannot connect to server: s d\n, htmlspecialchars mysql_error , mysql_errno ; } else { die Cannot connect to server: . htmlspecialchars php_errormsg . \n; } } if mysql_select_db db_name { die sprintf Cannot select database: s d\n, htmlspecialchars mysql_error conn_id, mysql_errno conn_id; } return conn_id; } ? Alt hough m ost PHP exam ples t hroughout t his book dont show t he ?php and ? t ags, I ve shown t hem as part of Cookbook.php here t o em phasize t hat include files m ust enclose all PHP code wit hin t hose t ags. The PHP int erpret er doesnt m ake any assum pt ions about t he cont ent s of an include file when it begins parsing it , because you m ight include a file t hat cont ains not hing but HTML. Therefore, you m ust use ?php and ? t o specify explicit ly which part s of t he include file should be considered as PHP code rat her t han as HTML, j ust as you do in t he m ain script . Assum ing t hat Cookbook.php is inst alled in a direct ory t hat s nam ed in PHPs search pat h as defined by t he include_path variable in t he PHP init ializat ion file , it can be used from a t est harness script , harness.php. The ent ire script looks like t his: ?php harness.php - test harness for Cookbook.php library include Cookbook.php; conn_id = cookbook_connect ; print Connected\n; mysql_close conn_id; print Disconnected\n; ? I f you dont have perm ission t o m odify t he PHP init ializat ion file, you can access an include file by specifying it s full pat hnam e. For exam ple: include usrlocalapachelibphpCookbook.php; PHP also provides a require st at em ent t hat is like include except t hat PHP reads t he file even if t he require occurs inside a cont rol st ruct ure t hat never execut es such as an if block for which t he condit ion is never t rue . PHP 4 adds include_once and require_once st at em ent s. These ar e like include and require except t hat if t he file has already been read, it s cont ent s are not processed again. This is useful for avoiding m ult iple-declarat ion problem s t hat can easily occur in sit uat ions where library files include ot her library files. A way t o sim ulat e single- inclusion behavior under PHP 3 is t o associat e a unique sym bol wit h a library and process it s cont ent s only if t he sym bol is not already defined. For exam ple, a library file, MyLibrary.php, m ight be st ruct ured like t his: ?php MyLibrary.php - illustrate how to simulate single-inclusion behavior in PHP 3 Check whether or not the symbol associated with the file is defined. If not, define the symbol and process the files contents. Otherwise, the file has already been read; skip the remainder of its contents. if defined _MYLIBRARY_PHP_ { define _MYLIBRARY_PHP_, 1; ... put rest of library here ... } end _MYLIBRARY_PHP_ ? Where Should PHP Include Files Be Installed? PHP script s oft en are placed in t he docum ent t ree of your web server, and client s can request t hem direct ly. For PHP library files, I recom m end t hat you place t hem som ewhere out side t he docum ent t ree, especially if like Cookbook.php t hey cont ain nam es and passwords. This is part icularly t rue if you use a different ext ension such as .inc for t he nam es of include files. I f you do t hat and inst all include files in t he docum ent t ree, t hey m ight be request ed direct ly by client s and will be displayed as plain t ext , exposing t heir cont ent s. To prevent t hat from happening, reconfigure Apache so t hat it t reat s files wit h t he .inc ext ension as PHP code t o be processed by t he PHP int erpret er rat her t han being displayed lit erally.

2.4.6 Python