2011-04-01 65 views
0

我正在尝试使用Dependency InjectionFactory类。我已经读了很多关于这方面的内容,并看到了很多例子。 。但我不认为我正在使用正确的(对于母校制造工厂类的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"; 
    }  
} 

回答

0

你试图在你的Conn返回一个对象上运行query功能构造函数,它不会发生。构造函数返回void。添加另一种方法,例如我在下面添加的getDatabaseObject方法以返回您的PDO对象。

class Conn { 
    function Conn() { 
     $conf = $this->config(); 
    } 

    public function getDatabaseObject() { 
     try { return new PDO($conf['dsn'], $conf['user'], $conf['pass']); } 
     catch (PDOException $e) { echo $e->getMessage(); } 
    } 
} 

class Factory { 
    // I think I'm using Dependency Injection here 
    function createUser($id = NULL) { 
     $c = new Conn(); 
     return new User($c->getDatabaseObject(), $id); 
    } 
} 
0

你传递你的用户构造一个连接和一个ID

return new User(new Conn(), $id); 

由于User类可是没有一个构造PHP激发基类的构造函数

function UserDAO (&$db, &$id = NULL) { 
    $this->db = &$db; 
    $this->id = &$id;; 
    } 

所以基本上你传递的UserDAO连接对象,当它想一个db对象

这就是为什么它试图将Conn对象

+0

我有点理解。我需要做些什么才能获得DB对象?我应该在我的UserDAO类上使用'__constructor'吗? – Steven 2011-04-01 16:17:03

+1

@Steven,因为你建议你应该使用'__construct()'方法作为你的构造函数,因为它使构造函数更加明显(很容易忘记类的名称,然后不知道它是一个构造函数),它也意味着如果您将来更改类名称,那么它只需更少一行代码即可进行更改。 – Nick 2011-04-04 13:22:43