我正在嘗試使用Dependency Injection和Factory類。我已經讀了很多關於這方面的內容,並看到了很多例子。 。但我不認爲我正在使用正確的(對於母校製造工廠類的DI需要工廠和依賴注入幫助
我無法查詢我的數據庫中,我得到的錯誤:
Fatal error: Call to undefined method Conn::query()
的問題是在
的getRows($sql)
功能,似乎我已經無法正確使用DI,它不能夠使用PDO
功能。
有人能指出我在正確的方向,也許看到我在做什麼錯了?
這是我的代碼到目前爲止。
$user = Factory::createUser();
$result = $user->getUsers();
print_r($result);
這裏是所有其他類:
class Factory {
// I think I'm using Dependency Injection here
function createUser($id = NULL) { return new User(new Conn(), $id); }
}
//Returns PDO conection and that's it.
class Conn {
function config($cfg_file = 'sl.config') {
/* The code here returns $conf array */
}
function Conn() {
$conf = $this->config();
try { return new PDO($conf['dsn'], $conf['user'], $conf['pass']); }
catch (PDOException $e) { echo $e->getMessage(); }
}
}
interface iUser {
public function getSomething();
}
// This is where I do all my SQL queries and return results.
class UserDAO {
private $db = NULL;
private $id;
function UserDAO (&$db, &$id = NULL) {
$this->db = &$db;
$this->id = &$id;;
}
public function getRows($sql)
{
$result = $this->db->query($sql); // <------- THIS IS NOT WORKING
$row = $result->fetch(PDO::FETCH_ASSOC);
return $row;
}
function getUsers($limit = 10) {
$sql ="SELECT * FROM users LIMIT $limit";
return $this->getRows($sql);
}
}
class User extends UserDAO implements iUser {
public function getSomething() {
echo "Something";
}
}
我有點理解。我需要做些什麼才能獲得DB對象?我應該在我的UserDAO類上使用'__constructor'嗎? – Steven 2011-04-01 16:17:03
@Steven,因爲你建議你應該使用'__construct()'方法作爲你的構造函數,因爲它使構造函數更加明顯(很容易忘記類的名稱,然後不知道它是一個構造函數),它也意味着如果您將來更改類名稱,那麼它只需更少一行代碼即可進行更改。 – Nick 2011-04-04 13:22:43