I'm trying to write a simple cart class and wondering how to use sessions to preserve the cart values.

Can I change session variables by reference to the instance, or should I just use $_SESSION for everything in my class?

That doesn't seem to look quite as good because I'm setting some variables for messages on every page... but nothing is stored in the session...

Guess I could really use a primer on using sessions within OOP! Thanks

class shoppingCart
{

var $messages = array();
var $errors = array();

var $currentUserId = false;

var $dbServer = "";
var $dbUser = "";
var $dbPass = "";
var $dbName = "";

function __construct()
{

	$this->dbConnect();
	$this->checkLogin();

	if(isset($_POST['cart'])) {
		$this->doCart();
	}
	if(isset($_POST['user'])) {
		$this->doUser($_POST['user']);
	}
}
function checkLogin() 
{
	session_start();
}
function doCart()
{
	$this->catalog = $this->getCatalog();
	foreach($this->catalog as $item => $details) 
	{
		if(array_key_exists($item, $_POST)) {
			$this->cart[$item]['quantity'] = (int)$this->cart[$item]['quantity'] + $_POST[$item];
			if($_POST[$item] == 0) {
				unset($this->cart[$item]);
			}
			$total += $this->cart[$item]['quantity'] * $this->catalog[$item]['price'];
		}
	}
	$_SESSION['cart'] = (array)$this->cart;
	$_SESSION['cartTotal'] = (int)$this->cartTotal = $total;

#### Why am I storing these twice here?? Which do I use on page x?


}

    Can I change session variables by reference to the instance, or should I just use $_SESSION for everything in my class?

    you can use a reference, but to make sure you don't create code the "miraculously" seems to change things outside I would make a reference to the session, not vice-versa, like so:

    //in the variables part
    private $_sess = array();
    
    //and in the constructor:
    $this->_sess = &$_SESSION;

    use like: $this->sess['myVal'] = 'whatever'; and the $SESSION gets changed accordingly at the same time

    It would be a good idea to replace the "var" with "private", "protected" or "public" to define the scope of the variables.

    That doesn't seem to look quite as good because I'm setting some variables for messages on every page... but nothing is stored in the session...

    this part is not clear to me. If you talk about standard messages: how about defining them as constants?

    Like so:

    define('MY_MESSAGE, 'Hello World!');

    not sure if that's what you want to achieve...

    About storing things twice...yes, why? If it is something that needs to get carried over to the next page: use a session variable, if not, don't.

    Bjom

      This was really helpful and got me through it. Thanks for posting!

        Write a Reply...