阅读了很多关于依赖注入的知识,现在我正在尝试做一些事情。我想到了一个简单的表单提交。基本上是一个表格,其标题为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
类创建连接并在容器中调用该类?
我真的不知道,随时告诉我你会怎么做,并举例说明如果你有任何。