Object Oriented Analysis and Design

Hi everyone
I have two classes a User and a Shopping cart which model a binary association between them.
In Order to implement it i have created two classes

A User class:

class User{
            protected $name ;
            protected $email;
            protected $shoppingCart;

           public function __construct($name , $email)
            {
                  $this->name =$name;
                  $this ->email =$email;
                  $this->shoppingCart=new ShoppingCart($this);

                                                           }

                 //other getter and setter functions

                                                           }

         class ShoppingCart{
            
                       //Array stores the list of products in the 
                                cart:
                            protected  $products = array();
                       // For storing the IDs, as a convenience:
                            protected $ids = array();
            
                      // protected user

                           protected $user;
                // Constructor just sets the object up for usage:

                    function __construct($user) {
	                                       $this->products = array();
	                                          $this->ids = array();
                                              $this->user =$user;
	                                             }


                 // functions to add or delete item

                                                          }

My Question is , is it ok for both user class and Shopping cart class to have an instance of each other so when I construct user , i construct its shopping cart in its constructor.
and when i construct the shopping cart , I pass the user infor in the shopping carts constructor to assign the shopping cart to the user.

How can i model this association properly.
Also i would have to access the users shopping cart to display its total price from main PHP script…in that case can i also make the ShoppingCart attribute of Users Class public

I get that the user has a reference to the shopping cart, but why does the shopping cart need a reference to the user?

I would recommend against it, as that would also allow people to remove the shopping cart from a user completely, or give them a completely different shopping cart.

Instead you could either:

  1. Create a getShoppingCart() method on the user that returns the shopping cart. That way you can read from it, but you can’t remove or replace it
  2. Add all shopping cart specific methods to the user, such as getShoppingCartTotal(), addToShoppingCart(), removeFromShoppingCart() etc

The second option involves a little but more work, but it doesn’t violate the law of Demeter which the first solution does.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.