Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用容器的依赖项注入_Php_Oop_Design Patterns_Dependency Injection_Ioc Container - Fatal编程技术网

Php 使用容器的依赖项注入

Php 使用容器的依赖项注入,php,oop,design-patterns,dependency-injection,ioc-container,Php,Oop,Design Patterns,Dependency Injection,Ioc Container,读了很多关于依赖注入的书,现在我正在尝试做一些事情。我想到了一个简单的表单提交。基本上是一个表单,标题为输入字段,正文为文本区域 然后我有一个容器,像这样: class IoC { protected $db; public static function newPost() { $post = new Post(); // Instantiate post class so we can use the methods in there $input = $p

读了很多关于依赖注入的书,现在我正在尝试做一些事情。我想到了一个简单的表单提交。基本上是一个表单,标题为
输入
字段,正文为
文本区域

然后我有一个容器,像这样:

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?
  }
}
正如你所看到的,我对连接应该来自哪里感到困惑。考虑到这一点,我想应该有一个单独的、可重用的
数据库
类来创建连接并在容器中调用该类


我真的不知道,请随意告诉我你将如何做,如果你有任何例子,请给出。

依赖注入背后的想法是,你可以直接注入任何依赖项。假设你有你的博士后课程。这个类(在您的例子中)依赖于数据库,因此您可以将数据库对象注入构造函数(或者setter,如果您愿意,请参阅symfony2了解更多信息)。反过来,您的数据库类需要参数来建立连接,您可以通过注入配置(提供者)对象来实现这一点(是的!)

您的容器只不过是一个管理对象并可能初始化它们的容器。容器的任务是初始化数据库对象,以便将其插入到Post对象中

我不知道你们的国际奥委会是做什么的,但若它是你们的容器,我不建议它私下里这样做。您可以将容器传递到您请求post对象的控制器