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

/*
 * Active record design pattern
 * accessing a row in a database
 *
 */

class ActiveRecord {

    protected $records = array();
    protected $key;
    protected $value;
    protected $keyValuePair = array();
    protected $counter = 1;
    protected $id = null;

    public function __set($key, $value) {
        $this->key = $key;
        $this->value = $value;
        $this->keyValuePair = array_merge($this->keyValuePair, array($key => $value));
    }


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

    public function create() {
        $this->keyValuePair = array_merge($this->keyValuePair, array('id' => $this->counter));
        array_push($this->records, array('table' => $this->table, 'data' => $this->keyValuePair));
        $this->resetKeyValuePair();
        $this->updateCounter();
    }

    public function update() {
        $records = array();
        foreach ($this->records AS $record) {
            if ($record['table'] == $this->table && $record['data']['id'] == $this->id) {
                $record['data'][$this->key] = $this->value;
            }
            array_push($records, $record);
        }
        $this->records = $records;
        $this->resetKeyValuePair();
    }

    public function findByName($name) {
        $records = array();
        foreach ($this->records AS $record) {
            if ($record['table'] == $this->table && $record['data']['fruit'] == $name) {
                $this->id = $record['data']['id'];
                return $this;
            }
        }
    }

    private function resetKeyValuePair() {
        $this->keyValuePair = array();
    }

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

}

class Item extends ActiveRecord {

    protected $fruit;
    protected $stock;
    protected $color;
    protected $table = 'items';

}

$item = new Item;
$item->fruit = 'apple';
$item->stock = 10;
$item->color = 'green';
$item->create();
$item->fruit = 'pear';
$item->stock = 20;
$item->create();

$fruit = $item->findByName('apple');
$fruit->stock = 50;
$fruit->update();

echo $fruit->dump();
?>


    

Outputs:


[{"table":"items","data":{"fruit":"apple","stock":50,"color":"green","id":1}},{"table":"items","data":{"fruit":"pear","stock":20,"id":2}}]



 

© 2018 assessmentee.com