I'm fairly new to classical inheritance as I mainly deal with ECMAScript and Python, though I do a fair bit of ( shudder ) PHP. I know it's heavily influenced by Java and other classical inheritance based languages.
Question:
I was taking a peek at a few classes in a framework and noticed that the 'new' keyword wasn't called ( directly at least ) to create an instance, but the public getInstance method was used to create the initial object.
Can someone explain the strategy behind this? And when should I use it for my own classes?
Relevant Code:
class FrontController {
public static $_instance;
public static function getInstance() {
if ( !(self::$_instance instanceof self) ) {
self::$_instance = new self();
}
return self::$_instance;
}
}
$front = FrontController::getInstance();
$front->route();
echo $front->getBody();
Full Code:
class FrontController
{
protected $_controller, $_action, $_params, $_body, $_url;
public static $_instance;
public static function getInstance()
{
if ( ! ( self::$_instance instanceof self) ) {
self::$_instance = new self();
}
return self::$_instance;
}
private function __construct() {
$this->uri = uri::getInstance();
if ( $this->uri->fragment(0) ) {
$this->_controller = $this->uri->fragment(0).'Controller';
}
else {
$config = config::getInstance();
$default = $config->config_values['application']['default_controller'].'Controller';
$this->_controller = $default;
}
if ( $this->uri->fragment(1) ) {
$this->_action = $this->_uri->fragment(1);
} else {
$this->_action = 'index';
}
}
public function route() {
$con = $this->getController();
$rc = new ReflectionClass( $con );
if ( $rc->implementsInterface( 'IController' ) ) {
$controller = $rc->newInstance();
if ( $rc->hasMethod( $this->getAction() ) ) {
$method = $rc->getMethod( $this->getAction() );
} else {
$config = config::getInstance();
$default = $config->config_values['application']['default_action'];
$method = $rc->getMethod( $default );
}
$method->invoke( $controller );
} else {
throw new Exception('Interface iController must be implemented');
}
}
public function getController() {
if ( class_exists( $this->_controller ) ) {
return $this->_controller;
}
else {
$config = config::getInstance();
$default = $config->config_values['application']['error_controller'].'Controller';
return $default;
}
}
public function getAction() {
return $this->_action;
}
public function getBody() {
return $this->_body;
}
public function setBody( $body ) {
$this->_body = $body;
}
}