TaylorOtwell
TaylorOtwell

Reputation: 7337

How to handle dependencies that aren't "real" dependencies?

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

I would like to do proper dependency injection on this class, however, I'm struggling with how to implement it in this scenario. The Validator doesn't need a database connection to function. All of the other validation checks work fine without a database connection. Right now, I have the option of specifying the connection using property injection. Or, if no connection is specified via property injection, I'm using the Service Locator pattern to resolve the default connection from the IoC container.

Am I doing it wrong? What is the proper way to handle class dependencies that aren't required for the class to function?

I currently consume the validator like so:

$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 e-mail address on the "users" table.

Upvotes: 4

Views: 210

Answers (2)

Andreas
Andreas

Reputation: 5335

Don't know if there is a right (or close to being right) answer to your question but here it goes.

As you noted in your question, since your validator does require a database connection, that is you don't rely on the implementation of an injected instance to 'do some work' then you might not require to implement DI.

You might not need it after all and only need to pass your DB Connection Handler or Reference to your database access layer to the method that needs it. This might require some changes in your code of course.

Upvotes: 0

Narf
Narf

Reputation: 14752

Make use of interfaces or abstract classes to load only the proper implementation for the current case. Personally, I've almost never had the need to use either of them, but they are designed specifically for solving dependancy problems.

Upvotes: 1

Related Questions