require 'mysql_db.php'; require_once 'query.php'; $db = new MySqlDb; $db->connect('host', 'username', 'pass'); $db->query('use content_management_system'); $query = new DBQuery($db); $query->prepare('SELECT fname,sname FROM users WHERE username=:1S AND pword=:2S AND expire_time<:3I'); try { if($query->execute("visualad", "apron", time()))->num_rows() == 1) { echo('Correct Credentials'); } else { echo('Incorrect Credentials / Session Expired'); } } catch (QueryException $e) { echo('Error executing query: ' . $e); } |
class DBQuery { ..... public function fetch_array() { if (! is_resource($this->result)) { throw new Exception('Query not executed.'); } return $this->db->fetch_array($this->result); } public function fetch_row() { if (! is_resource($this->result)) { throw new Exception('Query not executed.'); } return $this->db->fetch_row($this->result); } public function fetch_assoc() { if (! is_resource($this->result)) { throw new Exception('Query not executed.'); } return $this->db->fetch_assoc($this->result); } public function fetch_object() { if (! is_resource($this->result)) { throw new Exception('Query not executed.'); } return $this->db->fetch_object($this->result); } public function num_rows() { if (! is_resource($this->result)) { throw new Exception('Query not executed.'); } return $this->db->num_rows($this->result); } } |
public function __construct(DB $db) { $this->db = $db; } |
当使用类型提示时,你不仅可以指定对象类型,还可以指定抽象类和接口。
三、 抛出异常
你可能已经从上面的代码中注意到,你捕获的是一个称为QueryException(我们将在后面实现这个对象)的异常。一个异常类似于一个错误,然而却更具有一般性。描述一个异常的最好的方法是使用emergency。尽管一个emergency可以不会是“致命的”,但是还是必须处理它。当在PHP中抛出一个异常时,执行的当前范围很快地被终止,不管它是一个函数,try..catch块还是脚本本身。然后,该异常遍历调用栈―终止每个执行范围,直到或者在一个try..catch块中捕获它或者它到达调用栈的顶部―此时它将生成一个致命错误。
异常处理是PHP 5中的另外一个新特征,当与OOP联用时,它能够实现良好地控制错误处理和报告。一个try..catch块是一种处理异常的重要机制。一旦被捕获,脚本将会从异常被捕获和被处理的代码的下一行继续执行。
如果查询失败,你需要改变你的execute函数以抛出一个异常。你将抛出一个称为QueryException的定制异常对象―导致错误的DBQuery对象被传递给它。
列表3.抛出一个异常。
/** *执行当前查询 * * 执行当前查询―用提供的参数代替任何点位符 * . * * @参数: mixed $queryParams,... 查询参数 * @返回:资源A―参考描述执行查询的资源。 */ public function execute($queryParams = '') { //例如: SELECT * FROM table WHERE name=:1S AND type=:2I AND level=:3N $args = func_get_args(); if ($this->stored_procedure) { /*调用compile函数以得到查询*/ $query = call_user_func_array(array($this, 'compile'), $args); } else { /*一个存储过程没被初始化,因此,作为一种标准查询来执行之*/ $query = $queryParams; } $result = $this->db->query($query); if (! $result) { throw new QueryException($this); } $this->result = $result; /* 注意现在我们怎么返回对象本身,这使我们能够从这个函数的返回结果中调用成员函数 */ return $this; } |
class DBQuery { /** *在调用compile()或execute()之后存储查询的编译版本 * * @var string $compiledQuery */ protected $compiledQuery; /** * 返回编译的查询而不执行它。 * @参数:mixed $params,...查询参数 * @返回:字符串―编译的查询 */ public function compile($params='') { if (! $this->stored_procedure) { throw new Exception("存储过程没被初始化."); } /*代替参数*/ $params = func_get_args(); //得到函数参数 $query = preg_replace("/(?compile_callback($params, 1, "2")', $this->query); return ($this->compiledQuery = $this->add_strings($query)); //把字符串放回查询中 } public function getDB() { return $this->db; } public function getCompiledQuery() { return $this->compiledQuery; } } |
/** *查询异常 * *当试图执行一个查询时,如果一个错误发生,将由{@link DBQuery}对象抛出错误 */ class QueryException extends Exception { /** * 查询文本 * * @var字符串$QueryText; */ protected $QueryText; /** *来自数据库的错误号/代码 * * @var字符串$ErrorCode */ protected $ErrorNumber; /** *来自数据库的错误消息 * * @var字符串$ErrorMessage */ protected $ErrorMessage; /** *类构造器 * * @参数:DBQuery $db,是抛出异常的查询对象 */ public function __construct(DBQuery $query) { /*得到调用栈*/ $backtrace = $this->GetTrace(); /*把行和文件设置到错误实际发生的位置*/ if (count($backtrace) > 0) { $x = 1; /*如果查询类被继承,那么我们需要忽略由子类所进行的调用*/ while((! isset($backtrace[$x]['line'])) || (isset($backtrace[$x]['class']) && is_subclass_of($backtrace[$x]['class'], 'DBQuery')) || (strpos(strtolower(@$backtrace[$x]['function']), 'call_user_func')) !== false ) { /*循环执行,只要没有行号或调用的函数是DBQuery类的一个子类*/ ++$x; /*如果我们到达栈底,那么我们使用第一个调用者*/ if (($x) >= count($backtrace)) { $x = count($backtrace); break; } } /*如果上面的循环至少执行一次,那么我们可以把它减1以查找实际的引起错误的代码行 */ if ($x != 1) { $x -= 1; } /*最后,我们可以设置文件和行号,这应该可以反映出引起错误的SQL语句*/ $this->line = $backtrace[$x]['line']; $this->file = $backtrace[$x]['file']; } $this->QueryText = $query->getCompiledQuery(); $this->ErrorNumber = $query->getDB()->errno(); $this->ErrorMessage = $query->getDB()->error(); /*调用超类的异常构造器*/ parent::__construct('Query Error', 0); } /** *得到查询文本 * * @返回字符串查询文本 */ public function GetQueryText() { return $this->QueryText; } /** *得到错误号 * * @返回字符串错误号 */ public function GetErrorNumber() { return $this->ErrorNumber; } /** *得到错误消息 * * @返回字符串错误消息 */ public function GetErrorMessage() { return $this->ErrorMessage; } /** *当对象被转换为一个字符串时调用。 * @返回字符串 */ public function __toString() { $output = "Query Error in {$this->file} on line {$this->line}nn"; $output .= "Query: {$this->QueryText}n"; $output .= "Error: {$this->ErrorMessage} ({$this->ErrorNumber})nn"; return $output; } } |