Een tijd geleden heb ik me eens verdiept in het OOP, wat wij zeer goed bevalt. Ik heb nu voor diverse dingen standaardklassen geschreven, waardoor ik steeds meer tijd ga besparen tijdens het programmeren. Ik heb zojuist een klasse geschreven die de verzendkosten uitrekent voor een webwinkel. Zelf heb ik het gevoel dat ik op de goede weg ben met OOP, maar ik vroeg me af hoe anderen er over denken... Daarom vraag ik om jullie eerlijke mening :)
Mijn klasse:
<?php
/********************************************************************************\
//class MailingCosts will get mailCosts from database by given product-ids and
calculates mailingCost
/********************************************************************************/
class MailingCosts {
private $db;
private $table;
private $pKey;
private $columnForWeight;
private $products = array();
private $costs = array(); //For example array('kg' => 'price') '10' => '8.90', 30 => '12.50') IMPORTANT: Lowest key needs to be lowest weight
public function __construct(PDO $db, $table, $pKey, $columnForWeight) {
$this->db = $db;
$this->table = $table;
$this->pKey = $pKey;
$this->columnForWeight = $columnForWeight;
}
public function setProducts($products) {
$this->products = $products;
}
protected function getTotalWeight() {
$totalWeight = 0;
foreach($this->products as $product) {
$sql = "SELECT " . $this->columnForWeight . " FROM " . $this->table . " WHERE " . $this->pKey . " = :pKey";
$stmt = $this->db->prepare($sql);
$stmt->bindValue(':pKey', $product);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$totalWeight += $result[columnForWeight];
}
return $totalWeight;
}
public function getCosts() {
$totalWeight = self::getTotalWeight();
$totalCosts = 0;
$count = 0;
while($totalCosts == 0) {
foreach($this->costs as $weight => $cost) {
if($totalWeight < $weight) {
$totalCosts += $cost;
break;
}
}
if($totalCosts == 0) {
$count += end($this->costs);
$totalWeight -= key(end($this->costs));
}
}
}
}
?>
Uiteraard mag iedereen hem gebruiken. Alvast bedankt!