assessmentee.com

Home | Start test | Contact
 

Activerecord | Adapter | Decorator | DependencyInjectionContainer | Facade | Factory | Hydration | Inheritance | Iterator | Mapper | MVC | Observer | Prototype | Proxy | Registry | ServiceLocator | Singleton | Specification | Strategy | TableGateway | ZF1_TableGateway | ZF2_TableGateway |




    <?php

/*
 * Data mapper design pattern, advantages compared to
 * active record pattern: separation of business logic and
 * data storage, each object has single responsibility
 * 
 *
 */

class ItemMapper
{

    protected $records = array();
    protected $counter = 1;

    public function save(Item $item)
    {

	if (!is_null($item->id)) {
	    foreach ($this->records as $counter => $record) {
		if ($counter == $item->id) {
		    $this->record[$counter] = $item;
		}
	    }
	} else {
	    $item->id = $this->counter;
	    $this->records[$this->counter] = $item;
	    $this->updateCounter();
	}
    }

    public function findByName($name)
    {
	foreach ($this->records AS $record) {
	    if ($record->name == $name) {
		return $record;
	    }
	}
    }

    private function updateCounter()
    {
	$this->counter++;
    }

    public function dump()
    {
	return json_encode($this->records, true);
    }

}

class Item
{

    public $id;
    public $name;
    public $stock;
    public $color;

}

$mapper = new ItemMapper();

$item = new Item;
$item->name = 'apple';
$item->stock = 10;
$item->color = 'red';
$mapper->save($item);

$item = new Item;
$item->name = 'pear';
$item->stock = 20;
$item->color = 'green';
$mapper->save($item);

$apple = $mapper->findByName('apple');

$apple->stock = 50;
$mapper->save($apple);

echo $mapper->dump();



    

Outputs:


{"1":{"id":1,"name":"apple","stock":50,"color":"red"},"2":{"id":2,"name":"pear","stock":20,"color":"green"}}



 

© 2018 assessmentee.com