Кошница и продукти

Soul_Stealler

Registered
Просто тествах нещо анонимните функции в PHP.
Ако на някой му трябва елементарен код за кошница и продукти :)



Код:
<?php

class Product
{
	protected $name;
	public $price;

	public function __construct( $name, $price )
	{
		$this->name = $name;
		$this->price = $price;
	}
}


class Cart
{
	protected $client, $products, $cart;

	public function __construct( $client )
	{
		$this->client = $client;
	}

	public function setStorage( &$products )
	{
		$this->products = &$products;
	}

	public function addProduct( $id, $quantity = 1 )
	{
		if ( is_numeric( $quantity ) && $this->products[$id] )
			$this->cart[$id] = $this->cart[$id] ? $this->cart[$id] + $quantity : $quantity;
	}

	public function preview()
	{
		$cart = new stdClass;
		$cart->price = 0;
		$cart->products->unique = count( $this->cart );
		$cart->products->all = 0;

		$cart_ = $this->cart; // $this може да се използва в анонимните функции от PHP 5.4.0 нагоре

		$callback = function ( $product, $id )use ( &$cart, $cart_ )
		{
			$cart->price += $product->price * $cart_[$id];
			$cart->products->all += $cart_[$id];
		}
		;

		array_walk( $this->products, $callback );
		return $cart;
	}
}

$products['apple'] = new Product( 'Apple', 12 );
$products['banana'] = new Product( 'Banana', 10 );
$products['coconut'] = new Product( 'Coconut', 19 );
$products['egs'] = new Product( 'Egs', 5 );

$cart = new Cart( 'John Doe' );
$cart->setStorage( $products );

$products['bacon'] = new Product( 'Bacon', 11 );

$cart->addProduct( 'bacon' );
$cart->addProduct( 'bacon', 6 );
$cart->addProduct( 'apple', 3 );


print_r( $cart->preview() );
print_r( $cart );

?>
 

Горе