Well, regarding interfaces, consider the following.
PHP Code:
<?php
class Config
{
public function isDev()
{
// example
return ( $_SERVER['DEV'] == 1 );
}
}
class DomainObject
{
protected $config;
public function __construct( Config $config )
{
$this->config = $config;
}
public function logError( $message )
{
if ( $this->config->isDev() )
{
echo 'Error! <br/>';
echo '<pre>';
print_r( $message );
echo '</pre>';
exit;
} else {
mail( 'admin@site.com', 'Error', $message );
header( "Location: /404.htm" );
exit;
}
}
}
?>
For DomainObject, we don't really care that $config is a Config object, or a subclass of it. But, with how we've setup our script, all we care about is that $config has the isDev() method. Here's another approach using an interface instead
PHP Code:
<?php
interface iConfig
{
public function isDev();
}
class Config implements iConfig
{
public function isDev()
{
// example
return ( $_SERVER['DEV'] == 1 );
}
}
class DomainObject
{
protected $config;
public function __construct( iConfig $config )
{
$this->config = $config;
}
public function logError( $message )
{
if ( $this->config->isDev() )
{
echo 'Error! <br/>';
echo '<pre>';
print_r( $message );
echo '</pre>';
exit;
} else {
mail( 'admin@site.com', 'Error', $message );
header( "Location: /404.htm" );
exit;
}
}
}
?>
Looks almost the same - but this time DomainObject::logError expects config to use the interface iConfig. This means ANY object can be passed in as long as it implements the interface, so we're no longer forcing the user (code) to extend the Config class. Try to pass in anything else, and PHP will trigger a fatal error.
P.S. This is just an example :P
Bookmarks