我已經開始學習PHP類,接口,擴展以及與這些相關的東西。在會話中使用購物車類
在此之前,我只與函數一起工作,它開始與單獨的函數hundreads相當混亂。
根據我的需求將有多個類爲我的項目:
- 車類。這應該是相當通用的,因爲在某些時候,我可能需要將數據保存到數據庫而不是會話。
- 計算類。將會有大約15種產品和大約5種不同類型的計算。 (基於金額,基準價格,人均價格等)
- 數據庫類。這將用於從我的計算類的數據庫中獲取我的價格。
- 從通過HTML表單提交的數據(也用於更新購物車數量並返回實時計算價格)
然而MPDF創建PDF,那只是爲了給在暗示什麼我正在努力實現,所以它可能會讓你更好地理解我應該如何處理事情。
現在的實際問題。這是我的車類:
interface CartInterface {
public function addItem($id, $amount, $months);
public function updateItem($id, $amount, $months);
public function deleteItem($id);
public function countItems();
public function getCart();
public function ifIdExists($id);
}
class Cart implements CartInterface {
public $cart = array();
public function addItem($id, $amount, $months) {
if($this->ifIdExists($id)){
$this->updateItem($id, $amount, $months);
}
else {
$this->cart[$id]['id'] = $id;
$this->cart[$id]['amount'] = $amount;
$this->cart[$id]['months'] = $months;
}
}
public function updateItem($id, $amount, $months) {
$this->cart[$id]['id'] = $id;
$this->cart[$id]['amount'] = $amount;
$this->cart[$id]['months'] = $months;
}
public function deleteItem($id) {
unset($this->cart[$id]);
}
public function countItems() {
return count($this->cart);
}
public function getCart() {
return $this->cart;
}
public function ifIdExists($id) {
$exists = false;
if(array_key_exists($id, $this->cart)) {
$exists = true;
}
else {
$exists = false;
}
return $exists;
}
public function showCart() {
foreach($this->cart as $value) {
echo "<br />";
echo 'Id:'. $value['id'] ;
echo "<br />";
echo 'Amount:'.$value['amount'];
echo "<br />";
echo 'Months:'.$value['months'];
echo "<br />";
}
}
}
這已經幾乎我的車需要但這裏的功能問題:
我的HTML表單有輸入欄的每個項目,這決定簇量相應的項目將被訂購。在這種情況下,我需要單獨的addItem()和updateItem()嗎?因爲無論如何,新的值會重寫舊的。
什麼決定我應該在CartInterface中包含哪些方法?我知道任何使用CartInterface的類都被迫使用這些方法,但是我想強制一個類使用這些方法的原因是什麼?
最重要的問題是適應這個類來使用會話。正如我們所知道的,購物車沒有會話就沒有多大用處。我怎樣才能使用$ cart-> deleteItem()也從會話中刪除項目?我是否需要創建一個單獨的SessionCart類,它具有與購物車相同的方法但處理會話?
$cart = new Cart(); $cart->addItem('1', '30', '2'); $cart->addItem('2', '306', '12'); $cart->addItem('6', '306', '12'); $cart->deleteItem('1'); // Here i create a session array from the cart but cart's class methods won't work $cart = $cart->getCart(); $_SESSION['cart'] = $cart; $cart->deleteItem('1'); // This won't effect the session cart print_r($_SESSION['cart']);
我感謝所有幫助,也請大家指出不好的編碼習慣,所以大家閱讀這篇文章會學到一些東西。
長話短說:我應該用什麼方法才能讓這個Cart類與會話一起工作?
爲什麼'$ cart-> deleteItem('1')'不會影響會話購物車?如果它是任何其他PHP陣列存儲購物車,那麼它會影響它。 – apokryfos
在上述示例中,它不會從會話購物車中銷燬物品。這就是爲什麼我要求幫助,因爲我不知道我應該如何繼續。 :) – Griphon
'$ cart = $ cart-> getCart();'覆蓋您的購物車對象,包含在對象中的數組。這違反了封裝(換句話說,爲什麼在一個類中包裝一個數組,如果你打算之後處理這個數組呢?) – apokryfos