我也是班级和PDO的新手。我试图编写一个具有单独函数的类来连接数据库并关闭连接,以便在页面中我可以:
length(pattern)*length(text) elements
使用$db->connOpen
$db->connClose
我想问题是关于类语法比PDO更多,因为要将类似下面的查询发送到页面中,我需要再次实例化类class database
{
private $host = '';
private $db_name = '';
private $charset = '';
private $username = '';
private $password = '';
public function setHost($host) {
$this->host = $host;
}
public function setDbName($db_name) {
$this->db_name = $db_name;
}
public function setUser($username, $password) {
$this->username = $username;
$this->password = $password;
}
public function connOpen() {
try {
$dsn = "mysql:host=$this->host;dbname=$this->db_name;charset=$this->charset";
$db = new PDO($dsn, $this->username, $this->password, array(PDO::ATTR_PERSISTENT => true));
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo $e->getMessage();
}
}
public function connClose() {
$db = null;
}
}
,使与db的连接加倍。
PDO
我的问题是:
由于
答案 0 :(得分:1)
我正在使用一个singlton类,它给我db ojbect然后我使用该对象在其他类中查询;
[Measures].[Date2]
我使用db对象查询的类
<?php
class db{
/*** Declare instance ***/
private static $instance = NULL;
/**
*
* the constructor is set to private so
* so nobody can create a new instance using new
*
*/
private function __construct() {
/*** maybe set the db name here later ***/
}
/**
*
* Return DB instance or create intitial connection
*
* @return object (PDO)
*
* @access public
*
*/
public static function getInstance() {
if (!self::$instance)
{
self::$instance = new \PDO("mysql:host=".databaseHost.";dbname=".databaseName."", databaseUserName,databasePassword);;
self::$instance-> setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
self::$instance-> setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
}
return self::$instance;
}
/**
*
* Like the constructor, we make __clone private
* so nobody can clone the instance
*
*/
private function __clone(){
}
} /*** end of class ***/
?>
答案 1 :(得分:1)
出于某种原因,大多数想要学习OOP的人都是从一个实现单例并干扰错误处理的数据库包装器开始的。
我的提示是您将数据库连接视为任何其他变量:
DateTime
这称为依赖注入。
不要浪费时间和精力编写代码以避免有用的功能,例如:
当您真正拥有要在PDO上添加的真实功能时,只关心编写数据库包装器。我能想到:
addLocation: (location, tid) => {
location = LocationSchema.clean(location);
LocationSchema.validate(location);
var lid = Locations.insert(location);
Thoughts.update({_id: tid}, {$push: {locations: lid}});
}
个对象......即使这样,也要非常小心,不要让PDO变得更糟; - )