2012-03-15 51 views
2

我想了解如何使用PDO与“连接”类。PDO连接类/代码和类设计

class db { 

    private static $dbh; 

    private function __construct(){} 
    private function __clone(){} 

    public static function connect() { 
     if(!self::$dbh){ 
      self::$dbh = new PDO("mysql:host=localhost;dbname=database", "user", "password"); 
      self::$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
     } 
     return self::$dbh; 
    } 

    final public static function __callStatic($chrMethod, $arrArguments) { 
     $dbh = self::connect(); 
     return call_user_func_array(array($dbh, $chrMethod), $arrArguments); 
    } 
} 

我已经采取了上述从http://php.net/manual/en/book.pdo.php,并略作修改的变量,但我不知道我怎么那么这个数据库类中连接到PDO连接对象?

$dbh = new db; //intiate connection??? 

$stmt = $dbh->prepare("SELECT * FROM questions WHERE id = :id"); // or should I do db::prepare.. ??? 
$stmt->bindParam(':id', $_GET['testid'], PDO::PARAM_INT); 

if ($stmt->execute()) { 
    while ($row = $stmt->fetch()){ 
     print_r($row); 
    } 
} 

有什么想法吗?谢谢

+0

我不想理解你为什么在这里使用全局静态类方法。 – hakre 2012-03-15 15:37:58

回答

5

这或多或少是我如何做到的。我不确定这是否是最好的方式,但它对我有用。

我的工厂类是我的代码的核心。从这里我生成所有与我一起工作的课程。我的工厂类保存在一个单独的文件factory.class.php

通过拥有一个工厂类,我只需要包含类文件一次。如果我没有这个,我必须包含我的班级文件以供每个文件使用。如果稍后需要更新类文件名,我只需要在工厂类文件中进行更新。

创建工厂对象的另一个原因是减少了数据库连接的数量。

我每个类保存为单独的文件

厂类

include_once('person.class.php'); 
include_once('tracking.class.php'); 
include_once('costAnalyzis.class.php'); 
include_once('activity.class.php'); 

class Factory { 
    function new_person_obj($id = NULL) { return new Person(Conn::get_conn(), $id); } 
    function new_tracking_obj($id = NULL) { return new Tracking(Conn::get_conn(), $id); } 
    function new_costAnalyzis_obj() { return new CostAnalyzis(Conn::get_conn()); } 
    function new_activity_obj() { return new Activity(Conn::get_conn()); } 
}  

Connection类

// I have this class in the same file as Factory class 
// This creates DB connection and returns any error messages 
class Conn { 
    private static $conn = NULL; 

    private function __construct() {} 

    private static function init() { 
     $conf = self::config(); 
     try { 
     self::$conn = new PDO($conf['dsn'], $conf['user'], $conf['pass'], array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")); 
     } 
     catch (PDOException $e) { 
     // We remove the username if we get [1045] Access denied 
     if (preg_match("/\b1045\b/i", $e->getMessage())) 
      echo "SQLSTATE[28000] [1045] Access denied for user 'name removed' @ 'localhost' (using password: YES)"; 
     else 
      echo $e->getMessage(); 
     } 
    } 

    public static function get_conn() { 
    if (!self::$conn) { self::init(); } 
    return self::$conn; 
    } 

    // I used to get login info from config file. Now I use Wordpress constants 
    private static function config() { 
    $conf = array(); 

    $conf['user'] = DB_USER; //$config['db_user']; 
    $conf['pass'] = DB_PASSWORD; //$config['db_password']; 
    $conf['dsn']  = 'mysql:dbname='.DB_NAME.';host='.DB_HOST; 

    return $conf; 
    } 
} 

不同类对象

这些是你的课程。这是您处理数据的地方在我自己的代码中,我使用了三层架构,将业务层和数据对象层的表示分离开来。

class Person extends PersonDAO { 

    function getPersonData($id) { 
    $result = parent::getPersonData($id); 

    // Here you can work with your data. If you do not need to handle data, just return result 
    return $result; 
    } 
} 


// I only have SQL queries in this class and I only return RAW results. 
class PersonDAO { 

    // This variable is also available from you mother class Person 
    private $db; 

    // Constructor. It is automatically fired when calling the function. 
    // It must have the same name as the class - unless you define 
    // the constructor in your mother class. 
    // The &$db variable is the connection passed from the Factory class. 
    function PersonDAO (&$db) { 
     $this->db = &$db; 
    } 


    public function get_data($id) { 
    $sql ="SELECT a, b, c 
      FROM my_table 
      WHERE id = :id"; 

    $stmt = $this->db->prepare($sql); 
    $stmt->execute(array(':id'=> $id)); 
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC); 

    return $result; 
    } 

    public function get_some_other_data() { 
    $sql ="SELECT a, b, c 
      FROM my_table_b"; 

    $result = $stmt->fetchAll(PDO::FETCH_ASSOC); 

    return $result;  
    } 
} 

对您的其他课程做同样的事情。

全部放在一起

请注意,我们只包含一个文件,该工厂的文件。所有其他类文件都包含在Factory类文件中。

// Include factory file 
include_once('factory.class.php'); 

//Create your factory object 
$person = Factory::new_person_obj(); 

//Get person data 
$data = $person->getPersonData('12'); 

// output data 
print_r($data); 
+0

非常感谢您的回复Steven。我得到“调用一个非对象的成员函数new_obj()in ...”我更新了sql查询和数据库信息......你能够简单地评论每个部分的作用吗?对不起,我是OOP的新手..! – Tim 2012-03-15 17:17:51

+0

我没有使用WP ..但是已经定义了这些变量。另外如何添加新的查询?非常感谢:) – Tim 2012-03-15 17:18:15

+0

我也试过,同样的错误... :( – Tim 2012-03-15 18:33:27

3

正如我所理解的,您希望有一个“连接类”实现PDO实例的延迟加载。然后你希望代码中的对象能够从代码中的每个地方访问该连接,从而有效地创建一个单例。

不要这样做。

您正在清除应用程序中的全局状态,并且所有启用DB的类都紧密耦合到连接类的NAME。

我会推荐一些不同的方法。正如@Steven暗示的那样,您应该使用工厂来创建需要数据库连接的对象。

这是一个简化的实现。

class DataMapperFactory 
{ 
    protected $provider = null; 
    protected $connection = null; 

    public function __construct(Closure $provider) 
    { 
     $this->provider = $provider; 
    } 

    public function create($name) 
    { 
     if ($this->connection === null) 
     { 
      $this->connection = call_user_func($this->provider); 
     } 
     return new $name($this->connection); 
    } 

} 

你可能会有点像这样使用:

$provider = function() 
{ 
    $instance = new PDO('mysql:......'); 
    $instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
    $instance->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); 
    return $instance; 
}; 

$factory = new DataMapperFactory($provider); 

现在每次执行$factory->create('SomeClass'),它将创建该类的一个新实例,并为它提供在构造适当的数据库连接。而且,当第一次执行时,它将打开与数据库的连接。