0Neji
0Neji

Reputation: 1128

Dependency Injection - Passing Objects Around

I'm currently creating something based on OOP principles and I'm trying to apply dependency injection. I'm aware that I'm possibly doing something wrong here, the whole DI thing seems to be more confusing that it probably is but I'm still struggling to quite get my head around it.

I've created a Form class which will output various form elements but the form class will need at least two other classes (created as objects) to function properly.

Here's how I've got it:

$config = new Config();
$db = new Database();
$html = new HTML();

$form = new Form($config, $db, $html);

This is just me playing around so Form may not need all of those things but I'm using them to illustrate the point.

Now, when I'm creating a form, I don't want to have to pass the three objects into it to use it. I could solve this with static methods etc but it's really not a path I'm wanting to go down.

So what's the best way to be able to use the three objects created earlier in the Form class?

I guess I'm wanting an almost global type of behavior to a certain extent.

I've found a couple of things talking about this and factories, IoC containers etc but nothing that explained it clearly and easily so any help with this would be great. Or even a link to an easy to understand tutorial or something as I've failed to find one myself.

I also found Pimple - could something like that be along the right lines?

Upvotes: 1

Views: 148

Answers (1)

Adder
Adder

Reputation: 5878

Well, if you don't pass the three objects in, you are not doing dependency injection.

To avoid the parameters again, you can write either a Wrapper class, or a factory class which has methods to create and return a form object. You could initialize rhe factory class with $config, $db, $html once and then use that for every form created.

So the process would look like this:

$factory= new Factory($config, $db, $html);
$form= $factory->createForm();

Upvotes: 3

Related Questions