The topic of dependency injection is one that’s been around for some time in object-oriented programming circles. Sometimes we see it in WordPress; sometimes we don’t.

I’m a fan of it but, honestly, though, I’m not always sure how much information to inject into a class. I mean, let’s say that we’re given two classes, and one holds information the other needs.

  • Do we inject no class into another class?
  • Do we inject only a piece of information (be it a string, integer, data structure, or whatever) into the other class?

I don’t think there’s a hard and fast rule for this, but it’s probably safe to say that it’s better to inject just the data you need. But then this raises a question of how do prepare the data to inject into a given class?

  • Do you create a method in one class and pass it into another?
  • Do you pass a piece of private or protected information into it?

Then again, I think it depends on if anything has to happen to the information before it’s passed into a class.

Anyway, I could go back and forth on this for the rest of the post and never come to a conclusion so why not work through some source code until there’s something reasonable.

Passing Data via Dependency Injection

Let’s start off by saying we have a main plugin class file and this class is responsible for maintaining information such as:

  • the path to the plugin,
  • the URL to the plugin,
  • whether or not the plugin is loaded,
  • the screen that’s currently being viewed,
  • and the classes to which it needs to broadcast (think pub/sub) certain pieces of information.

Perhaps a skeleton or a stub of the class might look like this:

Then let’s start really broad. Say that we want to take the entire class and pass it into one of the classes to which it’s broadcasting information.

If that were the case, then it might look like this:

But one of the challenges with this is that it passes far more information than necessary into another class. Furthermore, it passes information that includes information about the class into which its passing information.

Pass via Dependency Injection

So let’s say we want to take a step back and just pass one of the private pieces of information. This is simple, right? It ends up looking something like this:

And this may be completely sufficient for some cases. But, as mentioned earlier, there are also times in which we want to take the information, process it, and then pass it into a class.

To do this, we’d just define a method, have it process information, then pass the return value into the class that needs the information:

The idea behind this discussion came up when working on a code review for a recent project and talking through the various options in which information could be passed into a class.

So I started broad (despite what’s necessary even given the thought process above) and then narrowed it down into what’s only necessary.