2011-04-01 66 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