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);
}
}
精彩评论