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

/**
 * Hydrate an array by an object
 * Implemented in Zend Framework II
 */
class Produce {

    protected $name;
    protected $color;

    public function getColor() {
        return $this->color;
    }

    public function exchangeArray($data) {
        $this->name = $data['name'];
        $this->color = $data['color'];
    }

     public function getArrayCopy() {
        return get_object_vars($this);
    }

}


class ArraySerializable {

    public function hydrate(array $data, $object) {
        if (is_callable(array($object, 'exchangeArray'))) {
            $object->exchangeArray($data);
        } else {
            throw new Exception('exchangeArray expected');
        }
        return $object;
    }

    public function extract($object) {
        if (!is_callable(array($object, 'getArrayCopy'))) {
            throw new Exception('getArrayCopy expected');
        }
        return $object->getArrayCopy();
    }
}

$array = array('name' => 'pear', 'color' => 'green');

$hydrator = new ArraySerializable();

// hydrate the array as a produce object
$object = $hydrator->hydrate($array, new Produce());

echo sprintf('Color: %s <br>',$object->getColor());

// reversed; extract the object as an array
$data = $hydrator->extract($object);
echo sprintf('Name: %s <br>', $data['name']);
    

Outputs:


Color: green
Name: pear



 

© 2018 assessmentee.com