简体   繁体   English

使用容器进行依赖注入

[英]Dependency injection using a container

Read a lot about dependency injection and now I'm trying to make something. 阅读了很多有关依赖注入的内容,现在我正在尝试做点事情。 I thought of a simple form submit. 我想到了一种简单的表单提交方式。 Basically a form with a input field for the title and a textarea for the body. 基本上是一种表单,带有用于标题的input字段和用于正文的textarea

Then I have a container, like this: 然后我有一个容器,像这样:

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

This is the Post class: 这是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?
  }
}

As you can see, I'm confused as to where the connection should come from. 如您所见,我对连接的来源感到困惑。 Thinking about it I guess it would be sensible to have a separate, re-usable Database class that creates the connections and call that class in the container? 考虑一下,我想拥有一个单独的,可重用的Database类来创建连接并在容器中调用该类是明智的?

I really don't know, feel free to tell me how you would do it and give examples if you have any. 我真的不知道,请随时告诉我您将如何做,并举一些例子。

The idea behind dependency injection is that you literally inject any dependencies. 依赖项注入背后的想法是您实际上注入了任何依赖项。 Say you have your Post class. 假设您参加了Post课程。 This class -in your case- depends on the database, so you inject your Database object in the constructor (or setter if you please, see symfony2 for more info). 此类-根据您的情况-取决于数据库,因此您将Database对象注入到构造函数中(如果需要,可以将其注入setter,有关更多信息,请参见symfony2)。 Your Database class in it's turn, needs parameters to set up a connection, you can do this (yes!) by injecting a configuration (provider) object. 该数据库类又需要参数来建立连接,可以通过注入配置(提供程序)对象来做到这一点(是!)。

Your container is nothing more than a container managing the objects and possibly initialising them. 您的容器不过是管理对象并可能对其进行初始化的容器。 It's the task of your container to init your Database object so it can be inserted in your Post object. 容器的任务是初始化数据库对象,以便可以将其插入Post对象中。

I have no idea what your IoC does, but if it's your container I wouldn't recommend it to do that privately. 我不知道您的IoC会做什么,但是如果是您的容器,我不建议您私下进行。 You could make your container being passed on to your controller in which you ask for the post object. 您可以将您的容器传递到您要在其中请求post对象的控制器。

http://symfony.com/doc/current/book/service_container.html http://symfony.com/doc/current/book/service_container.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM