2009-10-29 131 views
1

如果我在我的php应用程序中连接到数据库的对象,可以说我正在使用mysqli作为我的数据库事务的对象。使用mysqli对象连接到使用php对象的mysql的最佳方法

例如:

$dbase = new mysqli('localhost','dbuser','dbpass','dbname'); 
$oresult = $dbase->query("SELECT `field` FROM `table` WHERE `otherfield` = 12;"); 
if($oresult->num_rows > 0) { 
    $row = $oresult->fetch_row(); 
    $data = $row[0]; 
} 

,但我有我想跟以dBASE另一个自定义对象。

<?php 
class Thing { 
    private $sql = ''; 
    public $results = ''; 

    public function __construct($sql) { 
     $this->sql = $sql; 
     $this->get_data(); 
    } 

    private function get_data() { 
     // get the stuff from the dbase using $this->sql 
     $this->results = 'whatever'; 
    } 
} 

$thing = new Thing("SELECT `field` FROM `table` WHERE 1"); 
// do whatever i want with $thing->results 
?> 

哪里有“//从使用$这个 - 与dBASE> SQL的东西”行,我会想连接到dBASE和获取数据。

是它最好创建一个新的mysqli对象(我看到,因为我需要得到传递到每个对象我有连接信息的问题),或者我可以以某种方式使用

引用对象我已经有了
global $dbase 

里面的get_data函数。

什么是最佳实践?

回答

1

为数据库连接创建包装类。包装可以是单例,也可以将mysqli连接存储在静态字段中。

class DB { 
    static public $_connection; 
    static function connection(...) { 
     if (! self::$_connection) { 
      self::$_connection = mysqli_connect(...); 
     } 
     return self::$_connection; 
    } 
} 

这也可以很容易地隔离用户证书,将它们存储在单个脚本或配置文件中。

而不是暴露连接的类DB,您可以使用DB类本身。将connection()转换为构造函数,编写prepare()方法和DBStatement类。

class DB { 
    static private $_connection; 
    function __construct(...) { 
     if (! self::$_connection) { 
      self::$_connection = mysqli_connect(...); 
     } 
    } 
    // returns an SQLStatement 
    function prepare($query) { 
    } 
} 
0

Mysql在建立连接时非常快速,所以我倾向于打开和关闭需要它们的连接。因此,如果我需要进行3次数据库查询以获得我需要返回的结果,那么我会这样做,但最后我会关闭该连接。

因此,我的控制器建立连接,调用需要的DAO,然后关闭它。

所以,如果这个Thing类只是要使用一个可能已经建立的连接,那么我只是建立连接,然后在这个类中关闭它。

传递给控制器​​外部的问题是,连接状态很容易迷路。

0

我有一个工厂类,通过提示为下一个调用进行连接和缓存。它将支持创建到同一个数据库的多个连接,以保持连接凭据分离。

class dbtool 
{ 
    private static $instance = false; 
    private static $connections= false; 

    private function __construct() { 
     if(! self::$instance) { 
      self::$instance = $this; 
      self::$connections = array(); 
     } 
    } 
    public function getInstance() { 
     if(! self::$instance) 
      self::$instance = new dbtool(); 
     return self::$instance; 
    } 
    public static function getConnection($hint) 
    { 
     if(! self::$instance) return false; 
     if(! array_key_exists($hint, self::$connections)) 
      self::$connections[ $hint ] = self::$connectByHint($hint); 
     return self::$connections[ $hint ]; 
    } 
    // a list of database creds by hint, etc... 
    private static function connectByHint($hint) {} 
} 

当脚本退出时发生关闭连接。如果你正在运行一个批处理程序,比如一个守护进程,你可能需要将连接本身封装在一个本地连接器类中,该类会执行一个mysqli_ping()来断言连接仍然存在,如果没有,请重新连接。

我也不鼓励将数据库密码保存为成员变量,因为它们可以使用print_r()或var_export()公开。你能猜到我对密码建议吗?