Getting started with PEAR - Part 1
YAWP, or Yet Another Web Programming (foundation for PHP applications), is a great way to make the jump to using the PEAR libraries in your application. According to the YAWP site:
When you use Yawp as the base of your application, get...
- A single easy-to-edit config file
- Automated authentication processing
- Automatic creation of common objects: (Database abstraction, Disk cache, Composite logger, Benchmark timer, Variable dumper)
- Safe accessor methods for PATH_INFO, GET, POST, and configuration values
Sounds good? Let's begin.
Installation:
Covered in
Getting started with PEAR.
Configuration:
The Yawp package includes a default config file, that is installed under the PEAR docs directory. On my system, I found the file here:
/usr/share/pear/doc/Yawp/docs/Yawp.conf-dist.php
The standard practice is to put this file in the base htdocs directory of your site, however I prefer to keep sensitive files outside of webspace, and this is supported also. Create Yawp.conf.php in you web document root, that contains a single line, starting with a slash, that is the path to your real config file:
/safe/path/outside/web/space/MyVhost.Yawp.conf.php
If you are running a number of vhosts, you can keep all your Yawp configs in the same directory.
Constants:
[CONSTANT]
# I uncommented these since they are useful to have site-wide constants that
# represent your host and directories.
# This way you can avoid hard-coding paths and move your site to another server/directory with
# minimum hassle.
# the base for all hrefs (e.g., '/~user')
HREF_BASE = /
DOCUMENT_ROOT = /var/www/vhost/htdocs/
HTTP_HOST = www.myvhost.com/
Next are auto-include files that run when certain conditions happen. Uncomment these if you want to trigger certain code to happen on conditions like login, logout, start or stop. These are followed by error reporting and session parameters.
[Yawp]
# scripts to execute on login
;login = /path/to/script1.php
;login = /path/to/script2.php
...
# error reporting level
error_reporting = %E_ALL%
# session parameters
session_start = true
session_lifetime = 0
session_path = %HREF_BASE%
session_domain = %HTTP_HOST%
session_secure = false
Next lets skip down to the Auth section. If you are running a site with user logins, you probably want to make use of this functionality. To use it, you would uncomment this section and customize it with your own settings. This example authenticates against a mysql database, Yawp also supports authenticating against a unix passwd file, LDAP or Samba passwords.
[Auth]
# general settings
container = DB
idle = 1800
expire = 3600
%AUTH_IDLED% = Your session has been idle for too long. Please sign in again.
%AUTH_EXPIRED% = Your session has expired. Please sign in again.
%AUTH_WRONG_LOGIN% = You provided an incorrect username or password. Please try again.
# DB container options for Auth
[Auth_DB]
# you must change these to match your DB structure
# here is a dsn example for mysql
dsn = mysql://username:password@localhost/database
table = auth
usernamecol = username
passwordcol = password
These settings assume you have a table 'auth' in database 'database', on server 'localhost'. Here is an example table definition:
CREATE TABLE auth (
username VARCHAR(50) default '' NOT NULL,
password VARCHAR(32) default '' NOT NULL,
PRIMARY KEY (username),
KEY (password)
);
Next on to the DB section. Just enter the details for your database connection.
[DB]
phptype = mysql
;dbsyntax =
;protocol =
hostspec = localhost
database = database
username = username
password = password
;proto_opts =
;option =
That is about it for the basic config options. There are some other sections commented out, if you are interested in any of those you can find more detail in the
Yawp documentation.
Hello World:
Now, on to writing your first page with Yawp.
<?php
require_once 'Yawp.php';
Yawp::start();
echo "<html><body>Hello world, hear my barbaric YAWP!</body></html>";
Yawp::stop();
?>
If you remember the auto-include section in the config, I mentioned includes could be triggered on start and stop, these correspond to Yawp::start() and Yawp::stop(), and would be appropriate places to put your html header and footer if you so desire.
Yawp Functions:
These functions are available from the Yawp object. Some of the common ones you will use are:
start() - see above
stop() - see above
getGet() - safely gets a GET variable
getPost() - safely gets a POST variable
getObject() - gets a PEAR class from Yawp (such as AUTH or DB), useful for doing PEAR functions not supported within Yawp directly.
authUsername() - returns the current username if authenticated.
Front Controller:
I recommend using a front controller (single point of entry) for your web application. For more general info on front controllers, here is a good
onlamp article. This is one page that will set up your environment and dispatch whatever pages need to display. Normally you would use the front controller to separate logic, flow control and layout, but for simplicity in this example I just dispatch a single view that will handle logic and layout. I'll explain the code in comments, so on to the code:
<?php
require_once 'Yawp.php';
Yawp::start();
// handle auth logout
$LOGOUT = Yawp::getGet('LOGOUT');
if ($LOGOUT) {
// return the PEAR Auth object from Yawp
$auth =& Yawp::getObject('Auth');
// Yawp doesn't have an authLogout func, so we call it directly
$auth->logout();
}
// are we logged in?
$auth_check = Yawp::authUsername();
if ($auth_check === null) {
// did you uncomment the Auth section in your config?
echo "Auth not enabled.";
} else if ($auth_check === false) {
// not logged in
// show the login form
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']?>">
<input type="hidden" name="LOGIN" value="1" />
<p>Username: <input type="text" name="username" />
<br />Password: <input type="password" name="password" />
<br /><input type="submit" value="Sign In" /></p>
<?php
// if there was an error...
if (Yawp::getAuthErr()) {
// ... print the message and clear the error
echo "<p>" . Yawp::clearAuthErrMsg() . "</p>";
}
?>
</form><?
// show anything else on your homepage that is meant for guests only
} else {
// output the content of your site, that is only visible
// for users which have been authenticated successfully.
// show username and logout link
printf("<div class=lighttext>Welcome user <b>%s</b> </div>\n", $auth_check );
echo "<A HREF=\"".$_SERVER['PHP_SELF']."?LOGOUT=1\">Log out</A>";
// I want to see any errors that happen, and break code execution
PEAR::setErrorHandling(PEAR_ERROR_DIE);
// fetch the DB object
$db =& Yawp::getObject('DB');
if (! $db) {
echo "Could not get database connection.";
} else {
// column data returned as an array indexed by column names
$db->setFetchMode(DB_FETCHMODE_ASSOC);
// to display certain data on a page, set the view variable
$view = Yawp::getGet('view');
if (empty($view))
$view = Yawp::getPost('view');
if (empty($view))
include 'page-default.php';
else {
switch ($view) {
case 'main':
include 'page-default.php';
break;
case 'custom':
include 'page-custom.php';
break;
default:
include 'page-default.php';
break;
}
}
}
}
?>
Next Part:
In the next part I'll be talking about DB queries and using HTML_QuickForm.