We are just starting to make a concerted effort to use dependency injection uniformly in our project, and I've run into an issue.
I'm writing a class to handle our MongoDB queries. I pass in a MongoClient as a dependency on the constructor, with no problem. But how do I handle a dependency when the variable necessary to instantiate the object is not available at the time of instantiation?
In particular, we have a wrapper for the MongoCollection method, findOne, that, if you pass a string in, currently (in the old code) turns that string into a MongoId with "new MongoId($_id)", and uses that for the find function.
From what I've learned about dependency injection, having "new MongoId" is a bad idea, and I know already that it will make it harder to write test cases for the function that converts a string to a MongoId.
But how do I handle the injection, when the MongoId class takes the id string on the constructor?
The only thing I've thought of that would work is to pass in a closure on the class constructor that does something like:
$getMongoId = function( $id ){
return new MongoId( $id );
};
with
class MyMongo
{
function __construct( MongoClient $client, Closure $mongoIdGetter){...}
}
[edited to fix this last part]
But is this the right way to handle it? Of course, if we are using a DiC, it we can do it, but requiring a closure for the constructor seems a bit much. Am I just being too dogmatic about injecting my dependencies? I could fix this easily by using "new MongoId($_id)" in the new class, I suppose.