我一直在嘗試使OOP PHP5代碼。但我認爲我的嘗試很笨拙。這些是我的問題:OOP php5結構
- 他們是一個更好,更精簡的方式來包含數據庫配置信息?
- 我可以以某種方式避免在每個函數中聲明$ db = new Db()嗎?
- 我應該使用PEAR作爲數據庫抽象層而不是Mysqli_database.php嗎?
Mysqli_database.php
<?php
class Db {
private $connection;
private function open_connection() {
if (file_exists('config.inc.php')) {
require('config.inc.php');
} else {
require('../config.inc.php');
}
try
{
$this->connection = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
}
catch (Exception $e)
{
throw $e;
}
}
private function close_connection() {
try
{
mysqli_close($this->connection);
}
catch (Exception $e)
{
throw $e;
}
}
public function query($query) {
try
{
$this->open_connection();
$result = mysqli_query($this->connection,$query);
return $result;
}
catch (Exception $e)
{
throw $e;
}
$this->close_connection();
}
public function fetchArray($query) {
$row = mysqli_fetch_assoc($query);
return $row;
}
public function count_rows($query) {
$row = mysqli_num_rows($query);
return $row;
}
public function rows_affected() {
$row = mysqli_affected_rows($this->connection);
return $row;
}
public function created_id() {
$row = mysqli_insert_id($this->connection);
return $row;
}
}
?>
Test_data.php
<?php
class Test_data {
public function show_text() {
$db = new Db();
$sql = $db->query("SELECT * FROM test_table");
$row = $db->fetchArray($sql);
echo 'This is the output: '.$row['text'];
}
}
?>
的config.inc.php
<?php
$dbname = 'database_name';
$dbhost = 'localhost';
$dbuser = 'database_user';
$dbpass = 'database_password';
?>
includes.php
<?php
require_once('config.inc.php');
require_once('Mysqli_database.php');
$db = new Db();
$test_data = new Test_data();
?>
的index.php
<?php
require_once('includes.php');
$test_data->show_text();
?>
權,配置信息的保存是一個口味問題,我喜歡使用CONSTANTS,那麼你知道它在全球範圍內不會改變。 – null 2009-08-17 17:29:37