我有一些困惑,我认为
我正试图让我的数据库连接对我的类文件中的函数可用,这样我就不需要把它注入到所有函数的调用中。我认为这是最简洁的方法,但我不确定的反弹
(简化)我有3个文件
1.)数据库连接文件(使用PDO)
2.)类文件与我的所有相关功能
3.)一个主要是HTML文件的文件,该文件包括所需的类和数据库连接,并启动所需的实例。
我的(简化/精简)类文件
<?php
class SPD_Products {
// varaibales
// start category variables
public $CategoryID;
public $CategoryName;
public $CategoryDescription;
public $CategoryActive;
public $CategoryDateAdded;
public $CategoryDateModified;
/*
* public function to set category varaiables
* @param int $categoryID
* @return true/false
*/
public function setCategory($CategoryID){
try {
if(isset($CategoryID) && is_int($CategoryID)){
if($result = $this->getCategoryByCategoryID($CategoryID)){
$this->CategoryID = intval($result->CategoryID);
$this->CategoryName = htmlentities($result->CategoryName);
$this->CategoryDescription = htmlentities($result->CategoryDescription);
$this->CategoryActive = intval($result->CategoryActive);
$this->CategoryDateAdded = intval($result->CategoryDateAdded);
$this->CategoryDateModified = intval($result->CategoryDateModified);
}
else {
return 'No Category';
}
}
else {
return false;
}
}
catch (Exception $e){
error_log('file = '.__FILE__.'.php class = '.get_class($this).' - function = '.__FUNCTION__.' - Exception caught: '.$e->getMessage());
return false;
}
}
/* ================================================================ */
/* ======================== SQL Queries =========================== */
/* ================================================================ */
/*
* public function to get all category details by CategoryID
* @param int $CategoryID
* @return array of results
*/
public function getCategoryByCategoryID($CategoryID) {
try{
global $db;
$query = "SELECT c.CategoryID, c.CategoryName, c.CategoryDescription, c.CategoryActive, c.CategoryDateAdded, c.CategoryDateModified, c.CategoryShopAvailable
FROM tCategories c
WHERE c.CategoryID = ?
AND c.CategoryActive = 1
AND c.CategoryShopAvailable = 1";
$stmt = $db->prepare($query);
$stmt->execute(array($CategoryID));
return $stmt->Fetch(PDO::FETCH_OBJ);
}
catch (PDOException $ex){
error_log('file = '.__FILE__.'.php class = '.get_class($this).' - function = '.__FUNCTION__.' - Exception caught: '.$ex->getMessage());
echo 'file = '.__FILE__.'.php class = '.get_class($this).' - function = '.__FUNCTION__.' - Exception caught: '.$ex->getMessage();
return false;
}
}
}
?>
我的数据库连接文件
// database login details
//* Define these so that they can't be changed
DEFINE ('DBUSER', 'xxxxx');
DEFINE ('DBPASS', 'xxxxx');
DEFINE ('DBHOST', '192.168.0.99');
DEFINE ('DBPORT', '3999');
DEFINE ('DBNAME', 'xxxxx');
try {
$db = new PDO('mysql:host='.DBHOST.'; port='.DBPORT.'; dbname='.DBNAME.'; charset=utf8', DBUSER, DBPASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $ex) {
echo 'An Error occured! '.$ex->getMessage(); //user friendly message
error_log('dbconn.php failed to connect to db - Exception caught: '.$ex->getMessage());
return false;
}
?>
我的测试页面
<?php
require_once('functions/dbconn.php');
require_once('class/products.class.php');
//$db = new Database(); // failed test
$products_obj = new SPD_Products();
$products_obj->setCategory($CategoryID = 1);
echo $products_obj->CategoryName;
?>
我尝试了各种方法将数据库连接到类中,但只有全局方法有效(我认为这不是一个好主意…)。以上确实有效,但我想要一个更好的方法。。。。我最终会有很多单独的类文件,所以不想在每个类文件中建立新的连接,因为我相信我只能这样做一次,而不需要使用全局,也不需要不断地注入它并将它从一个函数传递到另一个函数。
任何建议都将不胜感激!
那怎么办,把你的登录凭据放在一个php文件中:
<?php
// database login details
$config = array('DBUSER'=>'xxxxx',
'DBPASS'=>'xxxxx',
'DBHOST'=>'192.168.0.99',
'DBPORT'=>'3999'
'DBNAME'=> 'xxxxx');
?>
然后把dbconn.php
变成一个类,这样会更容易:
<?php
class DB {
function __construct() {
//some config here
require_once('functions/config.php');
}
function get_connection() {
try {
$db = new PDO('mysql:host='.$config['DBHOST'].'; port='.$config['DBPORT'].'; dbname='.$config['DBNAME'].'; charset=utf8'
, $config['DBUSER'], $config['DBPASS']);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $ex) {
echo 'An Error occured! '.$ex->getMessage(); //user friendly message
error_log('dbconn.php failed to connect to db - Exception caught: '.$ex->getMessage());
return false;
}
return $db;
}
}
?>
示例:
<?php
class SPD_Products {
require_once('functions/dbconn.php');
private $conn;
....
function __construct() {
$db = new DB();
$this->conn = $db->get_connection();
}
public function getCategoryByCategoryID($CategoryID) {
try{
$query = "....";
$stmt = $this->conn->prepare($query);//here
.......
}
catch (PDOException $ex){
.....
return false;
}
}
}
?>
这只是一种快速的方法,但当然你可以添加更多的逻辑,比如在创建新连接之前检查连接是否打开,等等……你明白了。。。