Connecting to the database server, when and where?

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Connecting to the database server, when and where?

Post by social_experiment »

I thought about connecting to database servers and some aspects that revolve around it. My particular interest is when (and to a lesser degree where) should the connection to the server be made. When you are connecting to a database server, when is the best place to do this?

If you are writing a plug-in that requires database connectivity, it’s probably best not to assume anything and connect to the db server afresh. A better alternative could be to check if a connection has already been made and if it still exists. With this information you could then determine whether to make a connection or not. Is there a php function that can check for an existing connection, or should I create a function for this purpose? Something similar to :

Code: Select all

<?php 
function checkServerConnection() {
  $pingServer = @mysql_ping();
  if (!$pingServer) { 
   //connect to the database
  }
}?>
 
Now to the where part. If I am using a class, what would be the best practise for connecting to a database.

Connect via the __construct()?

Code: Select all

<?php
class Pressume {
 
 function __construct() {
   $pingServer = @mysql_ping();
   if (!$pingServer) { 
    //connect to the database
   }
 }
 
}?>
 
Am I correct in saying that whenever a new Pressume object is instantiated, that a connection to the database will be made?

Connecting in the method.

Code: Select all

<?php
class Pressume {
 function checkForArbValue() {
     $this->connectToDb();
 
     //continue with rest of the function.
  }
    
}?>
Connecting on the page. If my page is called ‘something.php’, I make the connection on the page itself, through a method in my Pressume class.

Code: Select all

<?php
 $something = new Pressume;
 $something->connectToDb();
 
// etc.
?>
A final question, if you are writing the code and you don’t know the values of the login details (and adding these details is up to a 3rd party), what would be the best place to put them, inside an external file such as ‘details.php’ where each value is defined, or inside the class?
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
Post Reply