[英]Dependency injection using a container
閱讀了很多有關依賴注入的內容,現在我正在嘗試做點事情。 我想到了一種簡單的表單提交方式。 基本上是一種表單,帶有用於標題的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
類來創建連接並在容器中調用該類是明智的?
我真的不知道,請隨時告訴我您將如何做,並舉一些例子。
依賴項注入背后的想法是您實際上注入了任何依賴項。 假設您參加了Post課程。 此類-根據您的情況-取決於數據庫,因此您將Database對象注入到構造函數中(如果需要,可以將其注入setter,有關更多信息,請參見symfony2)。 該數據庫類又需要參數來建立連接,可以通過注入配置(提供程序)對象來做到這一點(是!)。
您的容器不過是管理對象並可能對其進行初始化的容器。 容器的任務是初始化數據庫對象,以便可以將其插入Post對象中。
我不知道您的IoC會做什么,但是如果是您的容器,我不建議您私下進行。 您可以將您的容器傳遞到您要在其中請求post對象的控制器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.