In re-writing my PHP framework vervPHP, I've created the following class:
class storage {
private static $instance;
public $db = null; // Holds a database connection object
public $user = null; // Holds user related information for custom auth
public $data = array(); // Array of data for storage
private function __construct(){
// Create the default array in $this->data....
}
public static function singleton() {
if (!isset(self::$instance)) {
$className = __CLASS__;
self::$instance = new $className;
}
return self::$instance;
}
// Getters, Setters and other stuff follows...
}
When my framework starts up, it looks like this:
index.php:
// Kick it off!
verv\init();
framework/verv/verv.php:
function init() {
$verv = storage::singleton();
loadConfig($verv);
loadRequest($verv);
connectDB($verv);
authenticateUser($verv);
loadModule($verv);
loadTemplate($verv);
renderPage($verv);
}
$verv
is passed by reference - so any changes are saved as it moves around.
My question is, do I need the singleton portion? And basically, am I doing it "right"? The code in question works (albeit it needs a little tidying) but I want to make sure that my storage class is as robust and efficient as possible.
init()
function. This looks like it should be the constructor of some class, I would consider setting$verv
as a class property so that you don't have to pass that as a parameter each time. It will serve the same purpose. I have no real experience with the Singleton pattern, however, from everything I've read this explanation seems right. \$\endgroup\$