2013-04-24 114 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