<?php


class BaseModel {

	var $fields;
	var $dao;
	var $fields_changed;

	function __construct( $dao ) {
		$this->dao = $dao;
		$this->fields_changed = array();
		$this->fields = array();
		// define fields
		//$this->fields['ID'] = '';
	}

	function get( $field ) {
		if (array_key_exists($field, $this->fields)) {
			return $this->fields[$field];
		}
		return null;
	}

	function set( $field, $value ) {
		if (array_key_exists($field, $this->fields)) {
			if ($this->fields[$field] != $value) {
				$this->fields_changed[$field] = true;
			}
			$this->fields[$field] = $value;
			return true;
		}
		return false;
	}

	function setDataFromDB( $data, $field_prefix = '' ) {
		foreach ($data as $k_field => $v_value) {
			if ($field_prefix != '') {
				if (substr($k_field, 0, strlen($field_prefix)) != $field_prefix) {
					continue;
				}
			}
			$this->fields[$k_field] = $v_value;
		}
	}

	/**
	 * Get Model as array.
	 *
	 * @return array array('key1' => 'value1', 'key2' => 'value2')
	 */
	function to_array() {
		$ret = array();
		foreach ($this->fields as $k_field => $v_value) {
			$ret[$k_field] = $this->get($k_field);
		}
		return $ret;
	}

	/**
	 * Get Model changed fields as array.
	 *
	 * @return array array('key1' => 'value1', 'key2' => 'value2')
	 */
	function changes_to_array() {
		$ret = array();
		foreach ($this->fields_changed as $k_field => $v_value) {
			$ret[$k_field] = $this->get($k_field);
		}
		return $ret;
	}

}
