HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Storage class, dependency injection and singletons

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
andstoragedependencyinjectionclasssingletons

Problem

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.

Solution

Read this post before using the singleton pattern: https://stackoverflow.com/a/4596323/1908639

You might find that it increases your initial development speed; however, the downsides tend to increase with the size/complexity of the project. I have personally maintained code that used singletons, and I found it difficult to test/reuse.

If you think there are any major advantages to the singleton approach, I would be interested in hearing them. I have not been able to find any beneficial use-cases in PHP web development, but I am definitely interested in hearing about them, if they exist.

Also, passing objects by reference should not be necessary in PHP 5 (source):


In PHP 5 there is a new Object Model. PHP's handling of objects has been completely rewritten, allowing for better performance and more features. In previous versions of PHP, objects were handled like primitive types (for instance integers and strings). The drawback of this method was that semantically the whole object was copied when a variable was assigned, or passed as a parameter to a method. In the new approach, objects are referenced by handle, and not by value (one can think of a handle as an object's identifier).

Context

StackExchange Code Review Q#13986, answer score: 2

Revisions (0)

No revisions yet.