Last active
December 17, 2015 10:59
-
-
Save stut/5599326 to your computer and use it in GitHub Desktop.
Interface example
This file contains hidden or 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 | |
// Logger interface. | |
interface iLogger | |
{ | |
public function __construct(); | |
public function write($str); | |
} |
This file contains hidden or 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 | |
// Example logger implementation that outputs to the console. | |
class Logger_Console implements iLogger | |
{ | |
public function __construct() | |
{ | |
// Do nothing. | |
} | |
public function write($str) | |
{ | |
echo $str.PHP_EOL; | |
} | |
} |
This file contains hidden or 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 | |
// Example logger implementation that logs to a file. | |
class Logger_File implements iLogger | |
{ | |
protected $_fp = null; | |
public function __construct() | |
{ | |
$this->_fp = fopen('/var/log/useful.log', 'wt'); | |
} | |
public function write($str) | |
{ | |
fwrite($this->_fp, $str.PHP_EOL); | |
} | |
} |
This file contains hidden or 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 | |
// This script creates a user first with the console logger, then with the file logger. | |
$user = new User(new Logger_Console()); | |
$user->create('Stuart', 'qwertyuiop'); | |
$user = new User(new Logger_File()); | |
$user->create('Tedd', 'zxcvbnm'); |
This file contains hidden or 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 | |
// Example class that takes a logger implementation. | |
class User | |
{ | |
protected $_logger = null; | |
public function __construct(iLogger $logger) | |
{ | |
$this->_logger = $logger; | |
} | |
public function create($username, $password) | |
{ | |
$_logger->write('Creating user named "'.$username.'" with the password "'.$password.'"'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment