2

I often use static "factory" methods to create objects from database.

class Job {
 protected $objDb;
 public function __construct($objDb) {
 $this->objDb = $objDb;
 }
 public static function LoadArrayByProjectId($intProjectId, $objDd) {
 //some code that loads the jobs
 $objJob = new Job($objDb);
 $arr[] = $objJob;
 //end of loop
 return $arr;
 }
 public static function LoadArrayByUserId($intUserId, $objDb) {
 //similar code
 }

}

So I try to use Dependency Injection by passing into the constructor the $objDb. The problem is the $objDb param in the static functions. It's very annoying to pass the param around.

How do you handle this case? Are there better solutions?

Kilian Foth
111k45 gold badges301 silver badges323 bronze badges
asked Jun 17, 2013 at 19:33

1 Answer 1

1

The fact that it looks odd to you may be a sign that it shouldn't be static. You can instead encapsulate the loader methods into a non-static class which also takes the database object in the constructor. To me this creates a more natural form of dependency injection (same way you did the Job class). The object asks for everything it needs to get the job done in the constructor and it doesn't have to be passed into each method.

class Loader {
 protected $objDb;
 public function __construct($objDb) {
 $this->objDb = $objDb;
 }
 public function LoadArrayByUserId($intUserId) {
 }
 public function LoadArrayByProjectId($intProjectId) {
 }
 }
answered Jun 18, 2013 at 7:34

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.