I need to get loads of data out of the database for a product (for example) and want to show it on a detail page, at present I’m getting the data from the database and setting turning them into properties then using getters to get them from the class (see below for an example), but surely there has to be a better way that I’m not aware of?
class.product.php
class Product {
private $db;
public function __construct($db) {
if (!$db instanceof Data_IDatabase) {
throw new Exception("Unknown database object.");
} else {
$this->db = $db;
}
}
public function getProduct($productId) {
$res = $this->db->query("SELECT title, keywords, description, info, live FROM product WHERE pid = '" . (int) $productId . "' LIMIT 1");
if ($this->db->numRows($res) > 0) {
$row = $this->db->fetchAssoc($res);
$this->title = $row['title'];
$this->keywords = $row['keywords'];
$this->desc = $row['description'];
//etc etc
}
}
public function getTitle() {
return $this->title;
}
public function getKeywords() {
return $this->keywords;
}
public function getDescription() {
return $this->desc;
}
//other get functions which get the above properties
}
product.php
<?php $product = new Product($db); ?>
<h1><?php echo $product->getTitle(); ?></h1>
<?php echo $product->getDescription(); ?>
<!-- rest of get methods here -->
?>