Im building a small MVC system and i want my controllers to be Singletons. I made the base controller “Controller” a singleton and every other controller extends from that. My Router processes the request from the URL and grabs the controller string name.
This is where im getting the private constructor error because i am trying to do this:
class IndexController extends Controller {
//the "Index" part comes from the url
}
class Controller {
private $instance;
/**
* Initializes a new Singleton Controller
*/
private function __construct() {
}
/**
* Get the instance of the Controller
*/
public static function getInstance(){
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
}
$className = "Controller";
$inst = new $className; //here is where i get the error
$inst = $className::getInstance() //also fails
I have done my research and i stumbled upon this (http://www.php.net/manual/en/reflectionclass.newinstancewithoutconstructor.php), however I am not sure if that will work or is the best method if it does.
$inst = new $className; //here is where i get the errorThis error is right, as the constructor is private.
$inst = $className::getInstance() //also failsThis error is also right, as this syntax is not allowed.
If you want your conrollers to be singletons, you can, but you need to “twist” the rules for that.
b.t.w
selfwithstaticas this will reference the actual controller you try to instantiate and not theControllerclass, asstaticreferences only the class it is written in.Twisting the rules: You will need to instantiate your controllers through a factory (it is a pattern). Usually the front controller is used for that.