jeudi 5 janvier 2017

PHP - Good design pattern for static database connection class

I have a "static" class which connects to database and has various functions. The current base layout is as follows:

class DB {

    private static $con;

    private function __construct() {};

    private function init() {
        if(is_null($con) {
            // Initialize database connection
        }
    }

    public static someMethod1() {
        self::init();
        // Do stuff
    }

    public static someMethod2() {
        self::init();
        // Do stuff
    }

    public static someMethod2() {
        self::init();
        // Do stuff
    }
}

My intention is to be easily be able to call these methods as: DB::someMethod1(). However, as you can see, I am having to cehck for initialization at every method beginning. Is this a good coding practice? Is there a better design pattern available? Initially I thought of builder pattern but that doesn't really fit here in my opinion.

Aucun commentaire:

Enregistrer un commentaire