2013-04-24 205 views
0

閱讀了很多關於依賴注入的知識,現在我正在嘗試做一些事情。我想到了一個簡單的表單提交。基本上是一個表格,其標題爲input字段,身體字段爲textarea使用容器進行依賴注入

然後,我有一個容器,就像這樣:

class IoC 
{ 
    protected $db; 

    public static function newPost() 
    { 
    $post = new Post(); // Instantiate post class so we can use the methods in there 
    $input = $post->getInput(); // Method that gets the POST values 
    $post->insertInput($input, $db); // Method that adds the post values to a database 
    } 
} 
//Call IoC::newPost(); on the page the form submits to 

這是Post類:

class Post 
{ 
    protected $db; 

    public function __construct($db) 
    { 
    $this->db = $db; 
    } 

    public function getInput() 
    { 
    // Should I get the post input here? Like $_POST['title'] etc. and put it 
    // into an array and then return it? 
    return $input; 
    } 

    public function insertIntoDB($db, $input) 
    { 
    // Should I hardcode the connection and query here? 
    } 
} 

正如你所看到的,我很困惑,當連接應來自。考慮它我想這是明智的,有一個單獨的,可重用的Database類創建連接並在容器中調用該類?

我真的不知道,隨時告訴我你會怎麼做,並舉例說明如果你有任何。

回答

1

依賴注入背後的想法是,你從字面上注入任何依賴關係。假設你有你的Post課程。這個類在你的情況下取決於數據庫,所以你在構造函數中注入你的數據庫對象(如果你願意,你可以參考symfony2瞭解更多信息)。你的數據庫類,需要參數來建立連接,你可以通過注入配置(提供者)對象來做到這一點(是!)。

你的容器不過是一個管理對象並可能初始化它們的容器。這是你的容器的任務來初始化你的數據庫對象,以便它可以插入到你的Post對象中。

我不知道你的IoC做什麼,但如果它是你的容器,我不會推薦它私下做。你可以讓你的容器傳遞給你的控制器,在其中你要求提供對象。

http://symfony.com/doc/current/book/service_container.html