We are just starting to make a concerted effort to evenly use dependency injection in our project, and I ran into a problem.
I am writing a class to handle MongoDB requests. I pass MongoClient as a constructor dependency, no problem. But how do I handle the dependency when the variable needed to instantiate the object is not available during instance creation?
In particular, we have a wrapper for the MongoCollection findOne method, which, if you pass a string, is currently (in the old code) turning that string into MongoId with the "new MongoId ($ _ id)" and uses this for the search function.
From what I learned about dependency injection, having a “new MongoId” is a bad idea, and I already know that it will be difficult to write test cases for a function that converts a string to MongoId.
But how do I handle the injection when the MongoId class accepts the id string in the constructor?
The only thing I thought about this is to go on to close the constructor of the class, which does something like:
$getMongoId = function( $id ){ return new MongoId( $id ); };
from
class MyMongo { function __construct( MongoClient $client, Closure $mongoIdGetter){...} }
[edited to fix this last part]
But is this the right way to handle this? Of course, if we use DiC, we can do this, but the closure requirement for the constructor seems a bit. Am I just too dogmatic about injecting my addictions? I could fix this easily using the "new MongoId ($ _ id)" in the new class. I guess.
php dependency-injection mongodb
Karptonite
source share