Domanda

In my shopping cart object , i have the collection of products

Now when user adds or removes the products , i have two options

  1. Either delete all old products and persist with new products
  2. Iterate with new product collection and see if thats already there. If not there then delete that object. If not there the add it

Which is better way

È stato utile?

Soluzione

The approach that I would take for deletes would be to build a function in the object that accepts an ID (such as a model number or database ID for the product) and that function then runs through it's own items and if the matching item is found to remove it.

As for adding new items, have a function that again accepts a the item ID and armed with that information fetches all the applicable data from the database and appends it to it's own collection.

You want to avoid deleting an object and making it again if you want to change something about it. Try to go with objects that have all the functionality to do what they need to do on their own.

Some example code will probably speak volumes more than the above:

class shoppingItem
{
    public $ID;
    public $name;
    public $price;
}

class shoppingCart
{
    public $items=array();
    public $totalValue;

    public function addItem($ID)
    {
        $this->items[]= new shoppingItem();
        // ... do database stuff to get item details
        $this->items[]->ID=$dataBaseRow['id'];
        $this->items[]->name=$dataBaseRow['name'];
        $this->items[]->price=$dataBaseRow['price'];
        $this->ammendTotal();
    }

    public function ammendTotal()
    {
        // loop all items and get total value.
        $var=myTotal;
        $this->totalValue=$var;
    }

    public function removeItem($ID)
    {
        for($i=0;$i<count($this->items);$i++)
        {
            if($this->items[$i]->ID==$ID)
            {
                // remove from array or update qty
            }
        }
        $this->ammendTotal();
    }
}

now, to add an item to the shopping cart, all you need to do is something like this:

$shoppingCart->addItem($someID);

The object will add it to itself, ammend it's total and carry on.

To remove an item, same deal:

$shoppingCart->removeItem($unwantedItemID);

and again, item deleted or quantity updated (however you chose to do it) and it's total is again updated.

Basically, keep it low maintenance. Never let an object have bad data in it (in this case such as totalValue not matching the sum of items within it) so write simple functions and re-use them where you can.

The calls you make from your main code should be as simple as possible and leave all the heavy lifting to the object. That way, you won't get any unexpected mistakes, your main code is easy to read/alter and you can have confidence in the objects.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top