Connecting to a database through the main?

Hey,

I would like to get the input on how some of you handle calling methods that require a database connection.

Do you create a connection instance (maybe using a singleton class) in every method you know will use a connection?

Or do you just create a method that will connect and place it into your main project and call it once?

ie


 public function connect() {} // handles connection

 $user = new User();
 $user->greet(); // doesn't require connection so no need to call connect method
 //the next method requires a connection so take care of that first
 $user->connect();
 
 if ($user->isLoggedIn())
   //Logged in

I think it’s the samething at the end of the day but it’s one less worry if you have connected to a database or not.

Let me know! thanks…

For simple project, i go with a singleton class. So everywhere in a code i use

$db = DB::get();

I don’t bother with connection stuff, class does all that. If a didn’t call $db -> query() function in a code, the connection is not even opened. It’s pretty simple:


class DB {
    protected static $instance;
    protected $connected = false;    

    private function __construct() { }

    public static function get() {
        if (!self :: $instance){ 
            self :: $instance = new self();
        }
        return self :: $instance;
    }

    public function query($sql){
        if (!$this -> connected) {
            $this -> connect();
        }

        // proceed with executing query
    }

    private function connect() {
        // mysql_connect() ...
        // if all fine,
        $this -> connected = true;
    }
}