Last active
August 29, 2015 14:04
-
-
Save MadaraUchiha/7e2cad9e6402eee7ebc0 to your computer and use it in GitHub Desktop.
PHP OOP Logger example
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 | |
interface ICanLog { | |
public function writeLine($line); | |
} | |
class FileLogger implements ICanLog { //Now I have to implement writeLine! | |
private $where; | |
public function __construct($where) { | |
$this->file = $where; | |
} | |
public function writeLine($line) { | |
file_put_contents($this->where, $line . "\n", FILE_APPEND); | |
} | |
} | |
class TestLogger implements ICanLog { | |
public function writeLine($line) { | |
//Do nothing, it's a test logger! | |
} | |
} | |
/* | |
As you can see, this log function doesn't know about | |
the existance of either the FileLogger or TestLogger | |
I can add any number of loggers I want without | |
changing the log function as long as they implement | |
the ICanLog interface. | |
*/ | |
function log(ICanLog $logger, $line) { | |
$logger->writeLine($line); //I don't know here which logger I'm handed, but I'm sure it'll have writeLine. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment