How to handle dependencies that are not β€œreal” dependencies?

I have a "Validator" class that can perform arbitrary checks on a data array. For example, check the string length of a given value in an array. The validator can also check the setpoint and see if it is unique in the database.

I would like to make the correct dependency injection in this class, however I am struggling with how to implement it in this scenario. Validator is not required connecting the database to the function. All other validation checks work fine without connecting to the database. Right now I have the option to specify a connection using property injection. Or, if the connection is not established by pasting properties, I use the Locator service template to resolve the default connection from the IoC container.

Am I doing it wrong? What is the correct way to handle class dependencies that are not required for the class to function?

I am currently using the validator as follows:

$rules = array( 'email' => 'required|unqiue:users', 'password' => 'required|confirmed', ); $validator = new Validator($attributes, $rules); 

Of course, the "unique" rule tells the validator to check the uniqueness of the email address in the "users" table.

+4
source share
2 answers

Use interfaces or abstract classes to load only the correct implementation for the current case. Personally, I almost never had to use any of them, but they are designed specifically to solve dependency problems.

+1
source

I do not know if there is a right (or close to the right) answer to your question, but here it goes.

As you noted in your question, since your validator requires a database connection, that is, you do not rely on the implementation of the injected instance to "do some work", then you may not require the implementation of DI.

In the end, you may not need it, and you just need to pass the handler or link to the database connection to the way that he needs. This may require some changes to your code.

0
source

All Articles