Example 1

Use case: Create a log mechanism using a database or a file interchangeably

<?php

interface LoggerInterface
{
    public function log(string $message);
}

 

Concrete Implementations 

<?php

class FileLogger implements LoggerInterface
{
    public function log(string $message)
    {
        return "log to file: $message";
    }

}

class DatabaseLogger implements LoggerInterface
{
    public function log(string $message)
    {
        return "log to database: $message";
    }
}

 

Client code

<?php

if ($loggerType == 'file') {
  $logger = new FileLogger;
} else if ($loggerType == 'database') {
  $logger = new DatabaseLogger;
}

$logger->log('Log this message');