我正在尝试使用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