Shopping Cart Design

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Begby
Forum Regular
Posts: 575
Joined: Wed Dec 13, 2006 10:28 am

Post by Begby »

kendall wrote:
The proper way to do it would be to override calculate_final_total in the discounted cart. That way if the customer changes his mind all you have to do is change your code so that the discounted cart us used and not have to worry about passing true or false to calculate_final_total.
So you can overwrite a function from the original class in the extended one?
would you believe me if i said i was just asking that same question?

thanks...

im not to good with OOP
Yes, you can override methods. This allows for polymorphism. This means that you can write your code to work with any shopping cart, it doesn't care what specific kind of shopping cart, just that you can put items into it, take items out of it, and get a total. All that matters is that all your shopping carts have the same functionality (implement the same interface).

Take the following as an example

Code: Select all

class Animal
{
  function makeSound()
  {
     die('you forgot to override me') ;
  }

  function sleep()
  {
     echo 'zzzzz' ;
  }
}


class Cat extends Animal
{
  function makeSound()
  {
     echo 'meow' ;
  }
}


class Chicken extends Animal
{
  function makeSound()
  {
    echo 'bawk bawk bigawk!' ;
  }
}


$animals = array() ;
$animals[] = new Chicken() ;
$animals[] = new Cat() ;
$animals[] = new Chicken () ;

foreach( $animals as $animal )
{
  $animal->makeSound() ;
}

// outputs 
// bawk bawk bigawk
// meow
// bawk bawk bigawk


Within foreach, you don't care what kind of animal it is, all that you care is that all animals have the same functionality. So you could quite easily add a donkey animal, stick it in your array, and the rest of the code will still work.

This is kinda how your shopping cart would work from the approach you took (there are other ways as well).

In PHP 5 you can enforce this a bit better by using interfaces and abstract classes

Code: Select all

interface IAnimal
{
  public function makeSound() ;
  public function sleep() ;
}

abstract class Animal implements IAnimal
{
  public function sleep()
  {
     echo 'zzzzz' ;
  }
}


class Cat extends Animal
{
 public  function makeSound()
  {
     echo 'meow' ;
  }
}


class Chicken extends Animal
{
  public function makeSound()
  {
    echo 'bawk bawk bigawk!' ;
  }
}
User avatar
kendall
Forum Regular
Posts: 852
Joined: Tue Jul 30, 2002 10:21 am
Location: Trinidad, West Indies
Contact:

Post by kendall »

Wow,

for a minute i was of the notion that you could have only overwritten class methods in PHP 5 and well...i'm using PHP 4

That interface looks cool...I know AS2 for flash so i'm more accustom to it in FLASH...

this is good...

thanks for the tip.
Post Reply