Skip to content

Instantly share code, notes, and snippets.

@stut
Last active December 17, 2015 10:59
Show Gist options
  • Save stut/5599326 to your computer and use it in GitHub Desktop.
Save stut/5599326 to your computer and use it in GitHub Desktop.
Interface example
<?php
// Logger interface.
interface iLogger
{
public function __construct();
public function write($str);
}
<?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;
}
}
<?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);
}
}
<?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');
<?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