【发布时间】:2013-04-24 11:09:36
【问题描述】:
阅读了很多关于依赖注入的内容,现在我正在尝试做一些事情。我想到了一个简单的表单提交。基本上是一个表单,其标题为 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 类来创建连接并在容器中调用该类是明智的吗?
我真的不知道,请随时告诉我你会怎么做,如果你有例子,请举个例子。
【问题讨论】:
标签: php oop design-patterns dependency-injection ioc-container