Re: PEAR DB examples?

From: Date: Fri, 08 Sep 2000 00:32:54 +0000
Subject: Re: PEAR DB examples?
References: 1  Groups: php.pear 
Request: Send a blank email to php-pear+get-235@lists.php.net to get a copy of this message
On Thu, 7 Sep 2000, Andrei Zmievski wrote: | Has anyone written a simple application that uses PEAR DB? If yes, I was | wondering if I could take a look at how you manage the DB calls. I've | been thinking about it today and, personally, I'd probably use a simple | wrapper class that calls DB::connect() in its constructor. But then | there are all sorts of other issues, like letting wrapper class check | for errors via DB:isError() or leaving those checks in the main code... | | So, anyone willing to share implementation examples? I usually approach this in one of three ways depending on what the application needs: 1. an auto-prepended file that sets the global variable $dbh (exiting on connection failure). 2. a function called assert_dbh() that sets the same global variable, but that is called only when needed (also from inside other functions/classes) 3. setting the global $dbh in an authentication function (that is called first on every page--that way you make sure that you don't get a database connection if you forgot to call the auth function). An example: --- auto_prepend file: require_once "DB.php"; require_once "DB/storage.php"; $DSN = "mysql://pear@localhost/pear"; if (!is_object($dbh)) { $dbh = DB::connect($DSN); } class Author extends DB_storage { function Author(&$dbh, $handle = false) { $this->DB_storage("authors", "handle", &$dbh); if ($handle) { $this->setup($handle); } } } function authReject($realm, $login_file = false) { Header("HTTP/1.0 401 Unauthorized"); Header("WWW-authenticate: basic realm=\"$realm\""); if ($login_file) { include($login_file); } else { print "access denied"; } exit; } function authRequire($level = 0) { global $PHP_AUTH_USER, $PHP_AUTH_PW, $DSN, $dbh, $userObject; if (!is_object($dbh)) { $dbh = DB::connect($DSN); } if (DB::isError($dbh)) { die("authRequire: ".$dbh->getMessage()); } $userObject = new Author(&$dbh, strtoupper($PHP_AUTH_USER)); if (DB::isError($userObject) || md5($PHP_AUTH_PW) != $userObject->password) { if ($level > 0) { authReject("PEAR administrator"); } else { authReject("PEAR maintainer"); } } } --- main file: authRequire(1); $obj = new Author(&$dbh); $err = $obj->insert($handle); var_dump($obj, $err); - Stig

« previous php.pear (#235) next »