try{
$customer = new inspired_customer();
$customer->setPk(9);
$customer->read();
// product ids to test
$ids = array(15,20,25);
foreach($ids as $id)
{
$object = new inspired_product();
$object->set('productid', $id);
$object->read();
$objects[] = $object;
}
// Setup the decorators
$decorator = new decorator(
array(
new inspired_product_decorator_discount_group($customer),
new inspired_product_decorator_discount_category(),
)
);
$decorator->setObjects($objects);
$decorator->decorate();
foreach($decorator->getObjects() as $product){
echo '
';
echo $product->getPk().' '.$product->prodname.'
';
var_dump($product->discounts);
}
}catch(Exception $e)
{
echo $e->getMessage().'
';
}
/*
* This is the object which ties it all together...
*/
class decorator extends object
{
protected $objects = array();
protected $decorators = array();
function __construct($decorators=false)
{
if($decorators) $this->setDecorators($decorators);
}
public function setObject(object &$object)
{
$this->objects[] = $object;
}
public function setObjects(&$objects)
{
if(is_array($objects)) foreach($objects as &$object)
{
$this->setObject($object);
}
}
public function getObjects(){
return $this->objects;
}
public function getObjectIds()
{
if(is_array($this->objects)) foreach($this->objects as $o)
{
$objectIds[] = $o->getPk();
}
return $objectIds;
}
public function setDecorator(decorator_base &$decorator)
{
$this->decorators[] = $decorator;
}
public function setDecorators($decorators)
{
if(is_array($decorators)) foreach($decorators as &$decorator)
{
$this->setDecorator($decorator);
}
}
function decorate()
{
if(is_array($this->decorators)) foreach($this->decorators as &$decorator)
{
$decorator->setObjects($this->objects);
$decorator->decorate();
}
}
}
class inspired_product_decorator_discount_group extends decorator_base implements decorator_interface{
function __construct(inspired_customer $customer)
{
$this->customer = $customer;
}
function &getData()
{
/*
* Lookup the customer group & assicoated discount rules.
*/
/*
* Note, can perform IN() queries based on these Ids;
*/
echo 'Calculating group discounts for productIds: '.implode(', ', $this->getObjectIds()).'
';
foreach($this->objects as $o) {
$data[$o->getPk()] = 5 + $o->getPk();
}
return $data;
}
function addData(&$object, &$data)
{
$object->discounts['group'] = $data;
}
}
abstract class decorator_base extends decorator implements decorator_interface
{
function decorate()
{
$data = $this->getData();
foreach($this->objects as $o)
{
// This decorator has further decoration to apply.
if(is_array($this->decorators)) foreach($this->decorators as $d)
{
$d->setObjects($data[$o->getPk()]);
}
$this->addData($o, $data[$o->getPk()]);
}
if(is_array($this->decorators)) foreach($this->decorators as $d)
{
$d->decorate();
}
}
}
interface decorator_interface
{
function decorate();
function &getData();
function addData(&$object, &$data);
}