我正在寻找一个更好的PDO数据库连接,我可以在不同的类中使用。例如,我当前的代码是这样的:
core.php
//Connecting to Database
try {
$db = new PDO("mysql:host=localhost;dbname=mydb", "project", "project123");
}
catch(PDOException $e) {
echo $e->getMessage();
}
类Core {
protected $db;
public function __construct(PDO $db) {
$this->db = $db;
}
function redirectTo($page,$mode = 'response',$message = '') {
if($message != '') {
header('Location: '.SITEURL.'/'.$page.'?'.$mode.'='.urlencode($message));
} else {
header('Location: '.SITEURL.'/'.$page);
}
exit();
}
}
除此之外,我还有两个类wall。php和ticker。php
class Wall {
protected $db;
public function __construct(PDO $db) {
$this->db = $db;
}
function addComment($uid, $fid, $comment) {
$time = time();
$ip = $_SERVER['REMOTE_ADDR'];
$query = $this->db->prepare('INSERT INTO wall_comments (comment, uid_fk, msg_id_fk, ip, created) VALUES (:comment, :uid, :fid, :ip, :time)');
$query->execute(array(':comment' => $comment, ':uid' => $uid, ':fid' => $fid, ':ip' => $ip, ':time' => $time));
$nofity_msg = "User commented on the post";
$setTicker = Ticker::addTicker($uid,$nofity_msg,'comment');
if($setTicker) {
Core::redirectTo('wall/view-'.$fid.'/','error','Oops, You have already posted it!');
} else {
Core::redirectTo('wall/view-'.$fid.'/','error','Oops, Error Occured');
}
}
}
和ticker.php是
class Ticker {
protected $db;
public function __construct(PDO $db) {
$this->db = $db;
}
function addTicker($uid,$msg,$type) {
$time = time();
$query = $this->db->prepare('INSERT INTO tickers (uid_fk, message, type, created) VALUES (:uid, :message, :type, :time)');
try {
$query->execute(array(':uid' => $uid, ':message' => $msg, ':type' => $type, ':time' => $time));
return $this->db->lastInsertId();
}
catch(PDOException $e) {
return 0;
}
}
}
现在我的问题是,我需要调用函数addComment(),并在该函数内部有一个函数addTicker()在类Ticker中存在的进一步调用。这将导致Db连接问题,因为已经有一个Db实例在前面的类中创建了。我不知道该如何解决这个问题。
这是我在主索引文件中使用的代码:$core = new Core($db);
$ticker = new Ticker($db);
$wall = new Wall($db);
$wall->addComment($uid, $fid, $add_comment); // This statement is not working.. :(
我的意图是有一个通用的主DB连接,并进一步在其他类中使用该连接。有更好的方法吗?
在前面的类中已经创建了一个db实例
这实际上是一个实例,但是被复制到两个变量中。
数据库连接出现问题
你能不能对这个问题再确定一点?你有什么特别的问题吗?