使用REQUIRE或依赖注入传递DB访问类?

时间:2015-06-08 20:32:48

标签: php pdo

已经提出了类似的问题,但我认为它们不包括我的案例。

我尝试了几种方法将db类传递给其他类进行访问,发现下面的方法效果很好。 我的问题是:这种方法有什么问题,依赖注入是否会成为更好的解决方案?

class Database{

    private $db_host = "localhost";
    private $db_user = "root";
    private $db_password = "";
    private $db_name = "dbName";    

    private $pdo;
    public  $instance;


    function __construct() {
        try{
            //create a PDO connection and assign it to some handler
            $this->pdo = new PDO('mysql:host='. $this->db_host.';dbname='. $this->db_name, $this->db_user,  $this->db_password);
            $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
           // echo "connected";
        } catch (PDOException $e) {
            exit("Error connecting to database". $e->getMessage());
        }
    }    


    public function getPDO(){
        return $this->pdo;
    }



}

class OtherClass{
    require_once 'Database.php';
    private $db_instance;
    private $dbh;

    function __construct() {
       $this->db_instance = new Database();
       $this->dbh = $this->db_instance->getPDO();
    } 


}

1 个答案:

答案 0 :(得分:0)

如果不需要,可以从中创建和销毁与数据库的连接的简单类。让我们折射你的代码abit。

首先创建一个可以轻松识别的类名,例如

class pdo_mysql{

它是一个pdo类,但基于mysql,接下来声明一些变量,(注释中的解释)

/*
* Description   -   The name of the database
*/
private $dbname;

/*
* Description   -   The database username
*/
private $dbuser;

/*
* Description   -   The database password
*/
private $dbpass;

/*
* Description   -   The database Host
*/
private $dbhost;

/*
* Description   -   The database driver 
* @Parameters   -   null
* To do         -  
* Notes: 
*/
private $dbdriver;
/*
* Description   -   Stores the connection to the database
*/
private $con;

然后让我们为我们的类定义构造函数:

/*
* Description   -   This is the default method that is called when this class is instantiated.
* @Parameters   -   dbhost|dbdriver|dbname|dbusername|dbpassword
*/
function __construct($dbhost, $dbdriver, $dbname, $dbuser, $dbpass){         
    $this->dbhost = $dbhost;
    $this->dbdriver = $dbdriver;
    $this->dbname = $dbname;
    $this->dbuser = $dbuser;
    $this->dbpass = $dbpass;
}

请注意,在实例化类时,会设置大多数类变量。 然后我们的连接功能:

/*
* Description   -   Creates a connection to the database
* Notes:        -   Returns true on success || string with an error msg on failure
*/
private function _connect(){
    try {
            $this->con = new PDO(''.$this->dbdriver.':host='.$this->dbhost.';dbname='.$this->dbname.'', $this->dbuser, $this->dbpass);
            $this->con->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
            $this->con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $this->con->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
            return true;
        }   catch (PDOException $e){    
            return $e->getMessage();
        }               
}

最后是一个断开我们与数据库连接的函数:

/*
* Description   -   Disconnects database connection
*/
private function _disconnect(){$this->con = null;return true;}

最后一个查询数据库的函数:

/*
* Description   -   Retrieves information from the database
*/
function _loadResult($data){}

这个类将使用预先填充的数据,因此我们为它创建一个初始化它的函数:(这应该在不同的文件/类中)

/*
* Description   -   Get the config options from a file and initiate the database object
* Notes:        -   Returns a new object of the database connection class on success | false on fail
                    the config file must contain the following values dbhost|dbengine|dbname|dbusername|dbpassword
*/
static public function getDbo(){
    if(!is_readable(/*path to your config file*/)){// lets check that the config file exists and is readable
        return 'ERROR - The config file is missing or its unreadable!';
    }

    $config = parse_ini_file(/*path to your config file*/);     
    if($config === false){//parse the config file and return an error incase the purse fails 
        return 'ERROR - Could not parse the config file!';
    }

//the following values are populated by the ones parsed from the config file
    $dbhost = $config['dbhost'];
    $dbclassprefix = $config['dbclassprefix'];
    $dbdriver = $config['dbdriver'];
    $dbname = $config['dbname'];
    $dbuser = $config['dbuser'];
    $dbpass = $config['dbpass'];        

    static $dbobject = null;//create the database object if all went well
    if(null === $dbobject){$dbclass = $dbclassprefix.$dbdriver;$dbobject = new $dbclass($dbhost, $dbdriver, $dbname, $dbuser, $dbpass);}
    return $dbobject;//return the database object
}

上述代码的案例用法:

$db = self::getDbo();//create the database object

    if(is_string($db)){//if the return value is a string, then thats an error
        //return an error
    }

    $res = $db->_loadResult($data);//call a function from the database class

这只是我头脑中的一个简陋示例,为您提供一些粗略的想法,但如果编码正确,它完全可以保证工作,使用上述类和函数,您可以将引擎更改为PDO_mysqli或其他另一种方法是更改​​配置文件中的值。希望你明白这个想法