閱讀了很多關於依賴注入的知識,現在我正在嘗試做一些事情。我想到了一個簡單的表單提交。基本上是一個表格,其標題爲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
類創建連接並在容器中調用該類?
我真的不知道,隨時告訴我你會怎麼做,並舉例說明如果你有任何。