Skip to content

Instantly share code, notes, and snippets.

@chris-scientist
Created May 12, 2021 17:07
Show Gist options
  • Save chris-scientist/67e383007f9c3ac41082ac84ac57df04 to your computer and use it in GitHub Desktop.
Save chris-scientist/67e383007f9c3ac41082ac84ac57df04 to your computer and use it in GitHub Desktop.
POC Singleton And Abstraction
<?php
/**
*
* Proof Of Concept in PHP.
*
* - Create a singleton class which is abstract, with abstract methods.
* - Abstract methods are implemented by other classes, with as many implementations as desired.
*
*
* @author chris-scientist
* @version 1.0
*
*/
class BreakLine {
public static $VALUE = "<br/>";
private function __constructor() {}
}
abstract class AbstractSingleton {
private static $DEFAULT_CLASS = 0;
private static $OTHER_CLASS = 1;
private static $instance = null;
private static $type = 0;
protected function __construct() {
echo ("parent constructor" . BreakLine::$VALUE);
}
public static function forceOtherClass() {
AbstractSingleton::$type = AbstractSingleton::$OTHER_CLASS;
}
public static function getInstance() {
if(
AbstractSingleton::$DEFAULT_CLASS == AbstractSingleton::$type &&
(
(
AbstractSingleton::$instance === null
) ||
(
! is_a(AbstractSingleton::$instance, "DefaultSingleton")
)
)
) {
AbstractSingleton::$instance = new DefaultSingleton();
} else if(
AbstractSingleton::$OTHER_CLASS == AbstractSingleton::$type &&
(
(
AbstractSingleton::$instance === null
) ||
(
! is_a(AbstractSingleton::$instance, "OtherSingleton")
)
)
) {
AbstractSingleton::$instance = new OtherSingleton();
}
return AbstractSingleton::$instance;
}
protected abstract function overrideFct();
public function run() {
$this->overrideFct();
}
}
class DefaultSingleton extends AbstractSingleton {
protected function __construct() {
parent::__construct();
echo ("default constructor" . BreakLine::$VALUE);
}
protected function overrideFct() {
echo ("default process" . BreakLine::$VALUE);
}
}
class OtherSingleton extends AbstractSingleton {
protected function __construct() {
parent::__construct();
echo ("other constructor" . BreakLine::$VALUE);
}
protected function overrideFct() {
echo ("other process" . BreakLine::$VALUE);
}
}
// ======================================================
//
// Test
AbstractSingleton::getInstance()->run();
echo (BreakLine::$VALUE . BreakLine::$VALUE);
AbstractSingleton::forceOtherClass();
AbstractSingleton::getInstance()->run();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment