Dependency Injection and Static Creator Methods for DB Connections in PHP

dependency-injectionPHP

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?

Best Answer

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) {
    }
 }