Skip to content

Instantly share code, notes, and snippets.

@MadaraUchiha
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MadaraUchiha/7e2cad9e6402eee7ebc0 to your computer and use it in GitHub Desktop.
Save MadaraUchiha/7e2cad9e6402eee7ebc0 to your computer and use it in GitHub Desktop.
PHP OOP Logger example
<?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