How/whether to use $this-> on a Class/Object pulled from a Session?
I'm currently refactoring a shopping Cart and I'm not sure whether I should be redeclaring it or using $this or maybe do something in the constructor or something when I pull it from the Session.
So e.g. my controller creates a new Cart, in order to call the 'add' method.
And then in the add method in the Cart I pull it from the session if it exists already.
Running the setTotals() method I pass the $cart object, but can I just use $this? Same happens in some other methods. Feel like I am creating extra Objects when I should be using the original.
Simplified version below, any ideas?
Controller
//AJAX POST TO ADD PRODUCT TO CART
public function postAddToCart(Request $request) {
$cart = new Cart();
$cart->add($request->id);
return response()->json(['status' => 'success', 'message' => 'Item Added'], 200);
}
And then Cart Class
class Cart {
public $items = null;
public $itemsTotal= 0;
// //GET CART = AJAX REQUEST
static function get() {
if(Session::has('cart')) { $cart = Session::get('cart'); } else { $cart = null;}
return response()->json(['cart' => $cart,], 200);
}
//ADD A PRODUCT TO THE CART
public function add($id) {
$cart = session()->pull('cart', function() { return new Cart(); });
$item = Panel::where('id',$id)->with('sub_panels')->with('upgrades')->first();
$cart->items[$item->id] = $item;
$cart->setTotals($cart);
}
private function setTotals($cart){
$cart->itemsTotal = 0;
$cart->customCharge = null;
$cart->setItemsIntervalPricing();
$cart->setCollectionPrice();
$cart->applyDiscountToTotals();
session()->put('cart', $cart);
}
Please or to participate in this conversation.