开发者

Php Session Object Interaction

I ask you for advice. I struggle with session/object interactions....

<?php
class ShoppingCart 
{

    public $products 

    public function __construct($session) {
        $this->products = $session['products']; 
    }

    public addProduct($id) {
        $this->products[] = new Product($id);
        $_SESSION['products'] = $this->products;
    }

}

session_start();
$shoppingCart = new ShoppingCart($_SESSION); 
$shoppingCart->addProduct(1);
?>

How would you write similar code? It's only the stub but I don't like my addProduct method and all 开发者_开发问答this code in general. Please don't be critical and help me improve it. Maybe there are some design patterns or examples of such interaction?


class ShoppingCart {

    private $products = array();

    public function __construct() {
        if (isset($_SESSION['products'])) {
            $this->products = &$_SESSION['products']; 
        }
    }

    public addProduct($id) {
        $this->products[] = new Product($id);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜