phpoopapidependency-injectionscope-resolution

Dependency injected or Scope Resolution Operator?


I didn't find a similar question, so I apologize if it already exists.

In my system I want a number of function libraries to ease a number of tasks across the whole system. That could be validating an e-mail. There's no reason to write the full regular expression each time if I can have a function do it, so I only need to change things and fix errors in one place.

Say I write a class called Files_Tools.

I can make it work both by dependency injecting an instance of this class into the objects that needs functions from this class. But I can also write the Files_Tools class with static functions and access them with the scope resolution operator. But as I have come to understand one of the major things about DI (dependency injection) is to avoid this kind of "global use". So my logic tells me to go with the DI approach. Yet, it still doesn't feel "right" that I'm doing it this way.

So my question is - What is regarded as the most correct way to create a toolset for a system? First of all, is it to make it as a class, instead of just plain functions? And then if it really is a class is the way to go, should I aim for the SRO or DI?

I understand there is probably not a definitive answer to this question, but I want to know if I'm completely off track or heading where many other coders would have done too.

Thanks in advance :)


Solution

  • DI makes it easier to unit test your classes and methods without dependency on the injected class... you can mock the injected object and manipulate its returns as appropriate for your tests. Scope resolution leaves you with this dependency so the tests aren't fully isolated.

    Many of my earlier projects use static classes for such functionality, and trying to write unit tests for them 6 years on is now a real chore because I didn't use DI.