MySQL connection between standalone classes

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mrblack
Forum Newbie
Posts: 6
Joined: Mon Oct 19, 2009 5:22 pm

MySQL connection between standalone classes

Post 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.]
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: MySQL connection between standalone classes

Post 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.
mrblack
Forum Newbie
Posts: 6
Joined: Mon Oct 19, 2009 5:22 pm

Re: MySQL connection between standalone classes

Post by mrblack »

Thank you very much. This is the way I want it to do.
Post Reply