数据库连接可用于所有类文件

时间:2014-09-25 00:00:22

标签: php mysql pdo

我认为我有些困惑

我正在尝试让我的数据库连接可用于我的类文件中的函数,因此我不需要将它注入所有调用函数。我认为这是做到这一点的最好方法,但我不确定拉力赛

(简化)我有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;

?>

我已尝试过将数据库连接引入类的各种方法,但只有全局方法有效(我不认为这是好的或干净的想法......)。以上确实有效,但我想要一个更好的方法.... 我最终会有很多单独的类文件,所以不想在每个类文件中建立一个新的连接,因为我确信我只能在不使用全局的情况下执行此操作,而无需继续注入并从函数中传递它发挥作用。

非常感谢任何建议!

1 个答案:

答案 0 :(得分:2)

怎么样,将您的登录凭证放入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;       
        }   
    }

}
?>

这只是快速的方式,但当然你可以添加更多的逻辑,例如在创建新的连接之前检查连接是否打开等等......你明白了......