Let's say I have a class that has several methods that depend on another object to do its duty. The difference is that they all depend on the same class of the object, but they need different instances of the class. Or, more specifically, each method needs a clean instance of the class, because the methods will change the state of the dependency.
Here is a simple example that I had in mind.
class Dependency { public $Property; } class Something { public function doSomething() {
Technically, I could do this.
class Something { public function doSomething(Dependency $dep = null) { $dep = $dep && is_null($dep->Property) ? $dep : new Dependency(); $dep->Property = 'blah'; } public function doSomethingElse(Dependency $dep = null) { $dep = $dep && is_null($dep->Property) ? $dep : new Dependency(); $dep->Property = 'blah blah'; } }
My problem is that I constantly have to check that the dependent object is being transferred in the correct state. The state is newly created. So instead, I was thinking of just doing something like this.
class Something { protected $DepObj; public function __construct(Dependency $dep) { $this->DepObj = $dep && is_null($dep->Property) ? $dep : new Dependency(); } public function doSomething() {
This allows me to get one instance of the object in the correct state, and I can just copy it if I need another. I am just wondering if that makes sense, or if I am over the fundamental guide regarding dependency injection and code checking.
source share