Page 1 of 1

MySQL connection between standalone classes

Posted: Mon Oct 19, 2009 5:45 pm
by mrblack
Hi,
I'm new here, so sorry if I'm asking something that's obvious for all of you :)

My problem:
I've got e.g. main class with 3 classes, each other independent, but they all need to access database. So now I started to think how to solve this case in the most effective way (I mean to not waste database connection). I thought that quite nice way could be if I'll create class Database (which extends mysqli class, maybe it'll some static class to ensure that only one instance can exist) with my own "query" method (some safer, that will check SQL string inserted). After that I'll pass reference of Database object created in the main class to those 3 classes. But I don't know if this is good idea.
Can anybody help me please? Thank you.


[Any please excuse me my English skills I'm not good at it either.]

Re: MySQL connection between standalone classes

Posted: Mon Oct 19, 2009 6:19 pm
by requinix
Use a Singleton design pattern.

Code: Select all

class Example {
 
    protected static $_instance;
 
    protected function __construct() {
        // constructor work
    }
 
    public static function instance() {
        if (!self::$_instance) self::$_instance = new self();
        return self::$_instance;
    }
 
    // other methods
 
}
Any time you want the class you do

Code: Select all

$db = Example::instance();
You can put that code anywhere you want and there will only be one database object used because it's being shared.

Re: MySQL connection between standalone classes

Posted: Mon Oct 19, 2009 6:28 pm
by mrblack
Thank you very much. This is the way I want it to do.