i'm not so sure about a connection being required of every class. i reckon it depends upon your application's architecture/design. in my web applications a subset of business classes provide model-services (classes that interact directly with the database and both abstract from and provide the view with a clean, simple interface to interact with the database) all extend a base business class whose constructor obtains a connection and whose destructor closes the connection.
here's that base class:
<?php
include_once('classes/AppInfo.php');
class BaseBo {
protected $appInfo;
protected $dbc;
function __construct() {
$this->appInfo = AppInfo::getInstance();
$this->dbc = mysqli_connect(
$this->appInfo->getMysqlHost(),$this->appInfo->getMysqlUser(),
$this->appInfo->getMysqlPassword(),$this->appInfo->getMysqlDatabase())
or die('Error connecting to database.');
}
function __desctruct() {
mysqli_close($this->dbc);
}
}
?>
and here's a snippet of a business class that extends BaseBo...
<?php
include_once('classes/bo/BaseBo.php');
include_once('classes/bean/Bike.php');
include_once('classes/bean/User.php');
class BikeManager extends BaseBo {
public function getBike(User $user, $bikeId) {
if (is_null($user) || $bikeId <= 0) return;
$userId = $user->getId();
$b = new Bike();
$b->setId($bikeId);
$sql = "select a.b_id, a.m_id, a.model, a.b_year, b.description " .
"from bike a, make b " .
"where a.u_id = $userId " .
"and a.b_id = $bikeId";
$result = mysqli_query($this->dbc, $sql);
$row = mysqli_fetch_array($result);
mysqli_free_result($result);
if ( ! is_null($row)) {
$b->getMake()->setId($row['m_id']);
$b->getMake()->setDescription($row['description']);
$b->setYear($row['b_year']);
$b->setModel($row['model']);
}
return $b;
} // getBike
} // BikeManager
?>
in this simple example, if a view component (i.e. a web page) requires bike information, the php snippet within it will create a new BikeManager and ask it for a particular bike's information.
there are some issues with this approach, but i'm a php noob and still learning about the internals of how the php engine, mysqli, etc actually work. i may change this approach to achieve better performance, resource management... having all this code localized to a specific application layer, though, lends itself well to change without polluting the other application layers.
jason