Skip to main content
3 of 6
added 2 characters in body
candied_orange
  • 119.7k
  • 27
  • 233
  • 369

I know I'm coming late to this party but I feel an important point is being missed.

Why should I do this:

class Profile {
    public function deactivateProfile(Setting $setting)
    {
        $setting->isActive = false;
    }
}

You shouldn't. But not because Dependency Injection is a bad idea. It's because this is doing it wrong.

Lets look at this things using code. We're going to do this:

$profile = new Profile();
$profile->deactivateProfile($setting);

when we get about the same thing out of this:

$setting->isActive = false; // Deactivate profile

So of course it seems like a waste of time. It is when you do it this way. This is not the best use of Dependency Injection. It's not even the best use of a class.

Now what if instead we had this:

$profile = new Profile($setting);

$application = new Application($profile);

$application.start();

And now the application is free to activate and deactivate the profile without having to know anything in particular about the setting that it's actually changing. Why is that good? In case you need to change setting. The application is walled off from those changes so you're free to go nuts in a safe contained space without having to watch everything break as soon as you touch something.

This follows the separate construction from behavior principle. The DI pattern here is a simple one. Build everything you need at as low a level as you can, wire them together, then start all the behavior ticking with one call.

The result is you have a separate place to decide what connects to what and a different place to manage what says what to whatever.

If that's not helpful to you then sure. DI, classes, object oriented programming, it's all a useless waste of time. Procedural code can solve all the same problems with less code.

Being able to make places in the code where I only have to think about a few things at the same time have really proved useful to me over the years. Sure it takes effort to make them. But once they're made I find working with them very relaxing. The people who maintain my code after I leave seem to like them too.

I know because I take the time to go back and visit my creations years later. You should to.

candied_orange
  • 119.7k
  • 27
  • 233
  • 369