Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

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?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

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) {
    }
 }
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.