Vinay Kumar

Dependency injection in PHP using interface

Dependency injection is a technique in which an object instance is passed as method parameter, thereby avoiding the initialization of the object inside the method. This enables loose coupling and also the “D” of S.O.L.I.D principles.

class FileLogger{
    public function log(string $message): void{
        printf("Logged to file with %s", $message);
    }
}

function logger($fileLogger){ 
    $fileLogger->log("test message");
}

$fileLogger = new FileLogger();
logger($fileLogger);
// Logged to file with test message

Here we notice that the parameter $fileLogger is dynamic and can be of any type. This will create error if anything other than FileLogger instance is passed. Going one step further let rewrite logger function.

function logger(FileLogger $fileLogger){ 
    $fileLogger->log("test message");
}

All looks good now. But wait! what if we need to introduce an additional logger let’s say DatabaseLogger and decide which one to pass as parameter depending on some condition. This is were interface can be made use of.

Interface holds abstract method and is like a contract for the class implementing it ie the class should have all the method defined in the interface.

Now going back to the logger example, let’s create an interface containing the log method and implement it in FileLogger and DatabaseLogger.


interface LoggerInterface{
  function log(string message);
}

class FileLogger implements LoggerInterface{
    public function log(string $message): void{
        printf("Logged to file with %s", $message);
    }
}

class DatabaseLogger implements LoggerInterface{
    public function log(string $message): void{
        printf("Logged to database with %s", $message);
    }
}

Finally let’s inject LoggerInterface in logger method. By doing so loose coupling, flexible object substitution and further flexible testing are achieved.