Created
April 28, 2013 02:14
-
-
Save trq/5475571 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Some logger interface | |
interface LoggerInterface | |
{ | |
public function log($message); | |
} | |
// Some class that relies upon the LoggerInterface interface | |
class Foo | |
{ | |
protected $logger; | |
public function __construct(LoggerInterface $logger) | |
{ | |
$this->logger = $logger; | |
} | |
public function bar() | |
{ | |
// Do domething, then write a log. | |
// $this->logger is guaranteed to have a log() method because it | |
// implements the LoggerInterface | |
$this->logger->log('Doing something'); | |
} | |
} | |
// Some classes that implement the LoggerInterfaces | |
class FSLogger implements LoggerInterface | |
{ | |
public function log($message) | |
{ | |
// some code to write a log entry to the filesystem | |
} | |
} | |
class DBLogger implements LoggerInterface | |
{ | |
public function log($message) | |
{ | |
// some code to write a log entry to a database | |
} | |
} | |
// Foo can use either LoggerInterface implementation | |
$foo = new Foo(new DBLogger); | |
$foo->bar(); | |
// or | |
$foo = new Foo(new FSLogger); | |
$foo->bar(); | |
// And then of course using DI and IoC containers you would have | |
// these dependencies configurable somewhere and then simply call | |
// something like: | |
$foo = DI::get('foo'); | |
$foo->bar(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment