ejx
ejx

Reputation: 489

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.

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:

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?

I really don't know, feel free to tell me how you would do it and give examples if you have any.

Upvotes: 0

Views: 103

Answers (1)

Anyone
Anyone

Reputation: 2825

The idea behind dependency injection is that you literally inject any dependencies. Say you have your Post class. 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). 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.

I have no idea what your IoC does, but if it's your container I wouldn't recommend it to do that privately. You could make your container being passed on to your controller in which you ask for the post object.

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

Upvotes: 1

Related Questions