Skip to content
Snippets Groups Projects
SimpleORMap.class.php 83.4 KiB
Newer Older
<?php
/**
 * SimpleORMap.class.php
 * simple object-relational mapping
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of
 * the License, or (at your option) any later version.
 *
 * @author      André Noack <noack@data-quest.de>
 * @copyright   2010 Stud.IP Core-Group
 * @license     http://www.gnu.org/licenses/gpl-2.0.html GPL version 2
 * @category    Stud.IP
*/

class SimpleORMap implements ArrayAccess, Countable, IteratorAggregate
{
    const ID_SEPARATOR = '_';

    /**
     * table row data
     * @var array $content
     */
    protected $content = [];
    /**
     * table row data
     * @var array $content_db
     */
    protected $content_db = [];
    /**
     * new state of entry
     * @var boolean $is_new
     */
    protected $is_new = true;
    /**
     * deleted state of entry
     * @var boolean $is_deleted
     */
    protected $is_deleted = false;
    /**
     * name of db table
     * @var string $db_table
     */
    protected $db_table = '';
    /**
     * table columns
     * @var array $db_fields
     */
    protected $db_fields = null;
    /**
     * primary key columns
     * @var array $pk
     */
    protected $pk = null;

    /**
     * default values for columns
     * @var array $default_values
     */
    protected $default_values = [];

    /**
     * list of columns to deserialize
     * @var array key is name of column, value is name of ArrayObject class
     */
    protected $serialized_fields = [];

     /**
     * db table metadata
     * @var array $schemes;
     */
    public static $schemes = null;

    /**
     * configuration data for subclasses
     * @see self::configure()
     * @var array $config;
     */
    protected static $config = [];

    /**
     * aliases for columns
     * alias => column
     * @var array $alias_fields
     */
    protected $alias_fields = [];

    /**
     * multi-language fields
     * name => boolean
     * @var array $i18n_fields
     */
    protected $i18n_fields = [];

    /**
     * additional computed fields
     * name => callable
     * @var array $additional_fields
     */
    protected $additional_fields = [];

    /**
     * stores instantiated related objects
     * @var array $relations
     */
    protected $relations = [];

    /**
     * 1:n relation
     * @var array $has_many
     */
    protected $has_many = [];

    /**
     * 1:1 relation
     * @var array $has_one
     */
    protected $has_one = [];

    /**
     * n:1 relations
     * @var array $belongs_to
     */
    protected $belongs_to = [];

    /**
     * n:m relations
     * @var array $has_and_belongs_to_many
     */
    protected $has_and_belongs_to_many = [];

    /**
     * callbacks
     * @var array $registered_callbacks
     */
    protected $registered_callbacks = [];

    /**
     * contains an array of all used identifiers for fields
     * (db columns + aliased columns + additional columns + relations)
     * @var array $known_slots
     */
    protected $known_slots = [];

    /**
     * reserved indentifiers, fields with those names must not have an explicit getXXX() method
     * @var array $reserved_slots
     */
    protected static $reserved_slots = ['value','newid','iterator','tablemetadata', 'relationvalue','wherequery','relationoptions','data','new','id'];

    /**
     * assoc array used to map SORM callback to NotificationCenter
     * keys are SORM callbacks, values notifications
     * eg. 'after_create' => 'FooDidCreate'
     *
     * @var array $notification_map
     */
    protected $notification_map = [];

    /**
     * assoc array for storing values for additional fields
     *
     * @var array $additional_data
     */
    protected $additional_data = [];

    /**
     * assoc array for mapping get/set Methods
     *
     * @var array $getter_setter_map
     */
    protected $getter_setter_map = [];

    /**
     * indicator for batch operations in findEachBySQL
     *
     * @var bool $batch_operation
     */
    protected static $performs_batch_operation = false;

    /**
     * set configuration data from subclass
     *
     * @param array $config configuration data
     * @return void
     */
    protected static function configure($config = [])
    {
        $class = get_called_class();

        if (empty($config['db_table'])) {
            $config['db_table'] = strtolower($class);
        }

        if (!isset($config['db_fields'])) {
            if (static::tableScheme($config['db_table'])) {
                $config['db_fields'] = self::$schemes[$config['db_table']]['db_fields'];
                $config['pk'] = self::$schemes[$config['db_table']]['pk'];
            }
        }

        if (isset($config['pk'])
            && !isset($config['db_fields']['id'])
            && !isset($config['alias_fields']['id'])
            && !isset($config['additional_fields']['id'])
        ) {
            if (count($config['pk']) === 1) {
                $config['alias_fields']['id'] = $config['pk'][0];
            } else {
                $config['additional_fields']['id'] = ['get' => '_getId',
                                                           'set' => '_setId'];
            }
        }
        if (isset($config['additional_fields'])) {
            foreach ($config['additional_fields'] as $a_field => $a_config) {
                if (is_array($a_config) && !(isset($a_config['get']) || isset($a_config['set']))) {
                    list($relation, $relation_field) = $a_config;
                    if (!$relation) {
                        list($relation, $relation_field) = explode('_', $a_field);
                    }
                    if (!$relation_field || !$relation) {
                        throw new UnexpectedValueException('no relation found for autoget/set additional field: ' . $a_field);
                    }
                    $config['additional_fields'][$a_field] = ['get'            => '_getAdditionalValueFromRelation',
                                                                   'set'            => '_setAdditionalValue',
                                                                   'relation'       => $relation,
                                                                   'relation_field' => $relation_field];
                }
            }
        }
        if (isset($config['serialized_fields'])) {
            foreach ($config['serialized_fields'] as $a_field => $object_type) {
                if (!(is_subclass_of($object_type, 'StudipArrayObject'))) {
                    throw new UnexpectedValueException(sprintf('serialized field %s must use subclass of StudipArrayObject', $a_field));
                }
            }
        }

        foreach (['has_many', 'belongs_to', 'has_one', 'has_and_belongs_to_many'] as $type) {
            if (is_array($config[$type])) {
                foreach (array_keys($config[$type]) as $one) {
                    $config['relations'][$one] = null;
                }
            }
        }

        $callbacks = ['before_create',
                      'before_update',
                      'before_store',
                      'before_delete',
                      'before_initialize',
                      'after_create',
                      'after_update',
                      'after_store',
                      'after_delete',
                      'after_initialize'];

        foreach ($callbacks as $callback) {
            if (!isset($config['registered_callbacks'][$callback])) {
                $config['registered_callbacks'][$callback] = [];
            }
        }

        if ($config['db_fields'][$config['pk'][0]]['extra'] == 'auto_increment') {
            array_unshift($config['registered_callbacks']['before_store'], 'cbAutoIncrementColumn');
            array_unshift($config['registered_callbacks']['after_create'], 'cbAutoIncrementColumn');
        } elseif (count($config['pk']) === 1) {
            array_unshift($config['registered_callbacks']['before_store'], 'cbAutoKeyCreation');
        }

        $auto_notification_map['after_create'] = $class . 'DidCreate';
        $auto_notification_map['after_store'] = $class . 'DidStore';
        $auto_notification_map['after_delete'] = $class . 'DidDelete';
        $auto_notification_map['after_update'] = $class . 'DidUpdate';
        $auto_notification_map['before_create'] = $class . 'WillCreate';
        $auto_notification_map['before_store'] = $class . 'WillStore';
        $auto_notification_map['before_delete'] = $class . 'WillDelete';
        $auto_notification_map['before_update'] = $class . 'WillUpdate';

        foreach ($auto_notification_map as $cb => $notification) {
            if (isset($config['notification_map'][$cb])) {
                if (strpos($config['notification_map'][$cb], $notification) !== false) {
                    $config['notification_map'][$cb] .= ' ' . $notification;
                }
            } else {
                $config['notification_map'][$cb] = $notification;
            }
        }

        if (is_array($config['notification_map'])) {
            foreach (array_keys($config['notification_map']) as $cb) {
                $config['registered_callbacks'][$cb][] = 'cbNotificationMapper';
            }
        }

        if (I18N::isEnabled()) {
            if (isset($config['i18n_fields']) && count($config['i18n_fields']) > 0) {
                if (count($config['pk']) > 1) {
                    throw new Exception('Can not define i18n fields on a composite primary key');
                }

                $config['registered_callbacks']['before_store'][] = 'cbI18N';
                $config['registered_callbacks']['after_delete'][] = 'cbI18N';
            }
        } else {
            $config['i18n_fields'] = [];
        }

        array_unshift($config['registered_callbacks']['after_initialize'], 'cbAfterInitialize');

        $config['known_slots'] = array_merge(
            array_keys($config['db_fields']),
            array_keys($config['alias_fields'] ?: []),
            array_keys($config['additional_fields'] ?: []),
            array_keys($config['relations'] ?: [])
        );

        foreach (array_map('strtolower', get_class_methods($class)) as $method) {
            if (in_array(substr($method, 0, 3), ['get', 'set'])) {
                $verb = substr($method, 0, 3);
                $name = substr($method, 3);
                if (in_array($name, $config['known_slots']) && !in_array($name, static::$reserved_slots) && !isset($config['additional_fields'][$name][$verb])) {
                    $config['getter_setter_map'][$name][$verb] = $method;
                }
            }
        }
        self::$config[$class] = $config;
    }

    /**
     * fetch config data for the called class
     *
     * @param string $key config key
     * @return string value of config key (null if not set)
     */
    protected static function config($key)
    {
        if (!array_key_exists(static::class, self::$config)) {
            static::configure();
        }

        return self::$config[static::class][$key];
    }

    /**
     * fetch table metadata from db or from local cache
     *
     * @param string $db_table
     * @return bool true if metadata could be fetched
     */
    public static function tableScheme($db_table)
    {
        if (self::$schemes === null) {
            $cache = StudipCacheFactory::getCache();
            self::$schemes = unserialize($cache->read('DB_TABLE_SCHEMES'));
        }
        if (!isset(self::$schemes[$db_table])) {
            $db = DBManager::get()->query("SHOW COLUMNS FROM $db_table");
            while($rs = $db->fetch(PDO::FETCH_ASSOC)){
                $db_fields[strtolower($rs['Field'])] = [
                    'name' => $rs['Field'],
                    'null' => $rs['Null'],
                    'default' => $rs['Default'],
                    'type' => $rs['Type'],
                    'extra' => $rs['Extra']
                ];
                if ($rs['Key'] == 'PRI'){
                }
            }
            self::$schemes[$db_table]['db_fields'] = $db_fields;
            self::$schemes[$db_table]['pk'] = $pk;
            $cache = StudipCacheFactory::getCache();
            $cache->write('DB_TABLE_SCHEMES', serialize(self::$schemes));
        }
        return isset(self::$schemes[$db_table]);
    }

    /**
     * force reload of cached table metadata
     */
    public static function expireTableScheme()
    {
        StudipCacheFactory::getCache()->expire('DB_TABLE_SCHEMES');
        self::$schemes = null;
        self::$config = [];
    }

    /**
     * returns new instance for given key
     * when found in db, else null
     * @param string primary key
     * @return SimpleORMap|NULL
     */
    public static function find($id)
    {
        $class = get_called_class();
        $ref = new ReflectionClass($class);
        $record = $ref->newInstanceArgs(func_get_args());
        if (!$record->isNew()) {
            return $record;
        } else {
            return null;
        }
    }

    /**
     * returns true if given key
     * exists in db
     * @param string primary key
     * @return boolean
     */
    public static function exists($id)
    {
        $ret = false;
        $db_table = static::config('db_table');
        $class = get_called_class();
        $record = new $class();
        call_user_func_array([$record, 'setId'], func_get_args());
        $where_query = $record->getWhereQuery();
        if ($where_query) {
            $query = "SELECT 1 FROM `$db_table` WHERE "
                    . join(" AND ", $where_query);
            $ret = (bool)DBManager::get()->query($query)->fetchColumn();
        }
        return $ret;
    }

    /**
     * returns number of records
     *
     * @param string sql clause to use on the right side of WHERE
     * @param array params for query
     * @return number
     */
    public static function countBySql($sql = 1, $params = [])
    {
        $db_table = static::config('db_table');
        $db = DBManager::get();
        if ($has_join === false || $has_join > 10) {
            $sql = 'WHERE ' . $sql;
        }
        $sql = "SELECT count(*) FROM `" .  $db_table . "` " . $sql;
        $st = $db->prepare($sql);
        $st->execute($params);
        return (int)$st->fetchColumn();
    }

    /**
     * creates new record with given data in db
     * returns the new object or null
     * @param array $data assoc array of record
     * @return SimpleORMap
     */
    public static function create($data)
    {
        $record = new static();
        $record->setData($data, false);
        if ($record->store()) {
            return $record;
        } else {
            return null;
        }
    }

    /**
     * build object with given data
     *
     * @param array $data assoc array of record
     * @param bool $is_new set object to new state
     * @return static
     */
    public static function build($data, $is_new = true)
    {
        $class = get_called_class();
        $record = new $class();
        $record->setData($data, !$is_new);
        $record->setNew($is_new);
        return $record;
    }

    /**
     * build object with given data and mark it as existing
     *
     * @param $data array assoc array of record
     * @return static
     */
    public static function buildExisting($data)
    {
        return static::build($data, false);
    }

    /**
     * generate SimpleORMap object structure from assoc array
     * if given array contains data of related objects in sub-arrays
     * they are also generated. Existing records are updated, new records are created
     * (but changes are not yet stored)
     *
     * @param array $data
     * @return static
     */
    public static function import($data)
    {
        $class = get_called_class();
        $record_data = [];
        $relation_data = [];
        foreach ($data as $key => $value) {
            if (is_array($value)) {
                $relation_data[$key] = $value;
            } else {
                $record_data[$key] = $value;
            }
        }
        $record = static::toObject($record_data);
        if (!$record instanceof $class) {
            $record = new $class();
            $record->setData($record_data, true);
        } else {
            $record->setData($record_data);
        }
        if (is_array($relation_data)) {
            foreach ($relation_data as $relation => $data) {
                $options = $record->getRelationOptions($relation);
                if ($options['type'] == 'has_one') {
                    $record->{$relation} = call_user_func([$options['class_name'], 'import'], $data);
                }
                if ($options['type'] == 'has_many' || $options['type'] == 'has_and_belongs_to_many') {
                    foreach ($data as $one) {
                        $current = call_user_func([$options['class_name'], 'import'], $one);
                        if ($options['type'] == 'has_many') {
                            $foreign_key_value = call_user_func($options['assoc_func_params_func'], $record);
                            call_user_func($options['assoc_foreign_key_setter'], $current, $foreign_key_value);
                        }
                        if ($current->id !== null) {
                            $existing = $record->{$relation}->find($current->id);
                            if ($existing) {
                                $existing->setData($current);
                            } else {
                                $record->{$relation}->append($current);
                            }
                        } else {
                            $record->{$relation}->append($current);
                        }
                    }
                }
            }
        }
        return $record;
    }

    /**
     * returns array of instances of given class filtered by given sql
     * @param string sql clause to use on the right side of WHERE
     * @param array parameters for query
     * @return array array of "self" objects
     */
    public static function findBySQL($sql, $params = [])
    {
        $db_table = static::config('db_table');
        $class = get_called_class();
        $record = new $class();
        $db = DBManager::get();
        if ($has_join === false || $has_join > 10) {
            $sql = 'WHERE ' . $sql;
        }
        $sql = "SELECT `" . $db_table . "`.* FROM `" . $db_table . "` " . $sql;
        $ret = [];
        $stmt = DBManager::get()->prepare($sql);
        $stmt->execute($params);
        $stmt->setFetchMode(PDO::FETCH_INTO , $record);
        $record->setNew(false);
        while ($record = $stmt->fetch()) {
            // Reset all relations
            $record->cleanup();

            $record->applyCallbacks('after_initialize');
            $ret[] = clone $record;
        }
        return $ret;
    }

    /**
     * returns one instance of given class filtered by given sql
     * only first row of query is used
     * @param string sql clause to use on the right side of WHERE
     * @param array parameters for query
     * @return SimpleORMap|NULL
     */
    public static function findOneBySQL($where, $params = [])
    {
        if (stripos($where, 'LIMIT') === false) {
            $where .= " LIMIT 1";
        }
        $found = static::findBySQL($where, $params);
        return isset($found[0]) ? $found[0] : null;
    }

    /**
     * find related records for a n:m relation (has_many_and_belongs_to_many)
     * using a combination table holding the keys
     *
     * @param string value of foreign key to find related records
     * @param array relation options from other side of relation
     * @return array of "self" objects
     */
    public static function findThru($foreign_key_value, $options)
    {
        $thru_table = $options['thru_table'];
        $thru_key = $options['thru_key'];
        $thru_assoc_key = $options['thru_assoc_key'];
        $assoc_foreign_key = $options['assoc_foreign_key'];

        $db_table = static::config('db_table');
        $class = get_called_class();
        $record = new $class();
        $sql = "SELECT `$db_table`.* FROM `$thru_table`
        INNER JOIN `$db_table` ON `$thru_table`.`$thru_assoc_key` = `$db_table`.`$assoc_foreign_key`
        WHERE `$thru_table`.`$thru_key` = ? " . $options['order_by'];
        $db = DBManager::get();
        $st = $db->prepare($sql);
        $st->execute([$foreign_key_value]);
        $ret = [];
        $st->setFetchMode(PDO::FETCH_INTO , $record);
        $record->setNew(false);
        while ($record = $st->fetch()) {
            // Reset all relations
            $record->cleanup();

            $record->applyCallbacks('after_initialize');
            $ret[] = clone $record;
        }
        return $ret;
    }

    /**
     * passes objects for given sql through given callback
     *
     * @param callable $callable callback which gets the current record as param
     * @param string where clause of sql
     * @param array sql statement parameters
     * @return integer number of found records
     */
    public static function findEachBySQL($callable, $sql, $params = [])
    {
        if ($has_join === false || $has_join > 10) {
            $sql = "WHERE {$sql}";
        }

        $record = new static();
        $record->setNew(false);

        $db_table = static::config('db_table');
        $st = DBManager::get()->prepare("SELECT `{$db_table}`.* FROM `{$db_table}` {$sql}");
        $st->execute($params);
        $st->setFetchMode(PDO::FETCH_INTO , $record);

        // Indicate that we are performing a batch operation
        static::$performs_batch_operation = true;

        $ret = 0;
        while ($record = $st->fetch()) {
            // Reset all relations
            $record->cleanup();
            $record->applyCallbacks('after_initialize');

            // Execute callable on current record
            $callable(clone $record, $ret++);
        }

        // Reset batch operation indicator
        static::$performs_batch_operation = false;

        return $ret;
    }

    /**
     * returns array of instances of given class for by given pks
     * @param array array og primary keys
     * @param string order by clause
     * @return array
     */
    public static function findMany($pks = [], $order = '', $order_params = [])
    {
        $db_table = static::config('db_table');
        $pk = static::config('pk');
        $db = DBManager::get();
        if (count($pk) > 1) {
            throw new Exception('not implemented yet');
        }
        $where = "`$db_table`.`{$pk[0]}` IN ("  . $db->quote($pks) . ") ";
        return static::findBySQL($where . $order, $order_params);
    }

    /**
     * passes objects for by given pks through given callback
     *
     * @param callable $callable callback which gets the current record as param
     * @param array $pks array of primary keys of called class
     * @param string $order order by sql
     * @return integer number of found records
     */
    public static function findEachMany($callable, $pks = [], $order = '', $order_params = [])
    {
        $db_table = static::config('db_table');
        $pk = static::config('pk');
        $db = DBManager::get();
        if (count($pk) > 1) {
            throw new Exception('not implemented yet');
        }
        $where = "`$db_table`.`{$pk[0]}` IN ("  . $db->quote($pks) . ") ";
        return static::findEachBySQL($callable, $where . $order, $order_params);
    }

    /**
     * passes objects for given sql through given callback
     * and returns an array of callback return values
     *
     * @param callable $callable callback which gets the current record as param
     * @param string where clause of sql
     * @param array sql statement parameters
     * @return array return values of callback
     */
    public static function findAndMapBySQL($callable, $where, $params = [])
    {
        $ret = [];
        $calleach = function($m) use (&$ret, $callable) {
            $ret[] = $callable($m);
        };
        static::findEachBySQL($calleach, $where, $params);
        return $ret;
    }

    /**
     * passes objects for by given pks through given callback
     * and returns an array of callback return values
     *
     * @param callable $callable callback which gets the current record as param
     * @param array $pks array of primary keys of called class
     * @param string $order order by sql
     * @return array return values of callback
     */
    public static function findAndMapMany($callable, $pks = [], $order = '', $order_params = [])
    {
        $ret = [];
        $calleach = function($m) use (&$ret, $callable) {
            $ret[] = $callable($m);
        };
        $db_table = static::config('db_table');
        $pk = static::config('pk');
        $db = DBManager::get();
        if (count($pk) > 1) {
            throw new Exception('not implemented yet');
        }
        $where = "`$db_table`.`{$pk[0]}` IN ("  . $db->quote($pks) . ") ";
        static::findEachBySQL($calleach, $where . $order, $order_params);
        return $ret;
    }

    /**
     * deletes objects specified by sql clause
     * @param string $where sql clause to use on the right side of WHERE
     * @param array $params parameters for query
     * @return number
     */
    public static function deleteBySQL($where, $params = [])
    {
        $killeach = function($record) {$record->delete();};
        return static::findEachBySQL($killeach, $where, $params);
    }

    /**
     * returns object of given class for given id or null
     * the param could be a string, an assoc array containing primary key field
     * or an already matching object. In all these cases an object is returned
     *
     * @param mixed $id_or_object id as string, object or assoc array
     * @return static
     */
    public static function toObject($id_or_object)
    {
        $class = get_called_class();
        if ($id_or_object instanceof $class) {
            return $id_or_object;
        }
        if (is_array($id_or_object)) {
            $pk = static::config('pk');
            $key_values = [];
            foreach($pk as $key) {
                if (array_key_exists($key, $id_or_object)) {
                    $key_values[] = $id_or_object[$key];
                }
            }
            if (count($pk) === count($key_values)) {
                if (count($pk) === 1) {
                    $id = $key_values[0];
                } else {
                    $id = $key_values;
                }
            }
        } else {
            $id = $id_or_object;
        }
        return call_user_func([$class, 'find'], $id);
    }

    /**
     * interceptor for static findByColumn / findEachByColumn / countByColumn /
     * deleteByColumn magic
     * @param string $name
     * @param array $arguments
     * @throws BadMethodCallException
     * @return mixed
     */
    public static function __callStatic($name, $arguments)
    {
        $db_table = static::config('db_table');
        $alias_fields = static::config('alias_fields');
        $db_fields = static::config('db_fields');
        $class = get_called_class();
        $param_arr = [];
        $where = '';
        $where_param = is_array($arguments[0]) ? $arguments[0] : [$arguments[0]];
        $prefix = strstr($name, 'by', true);
        $field = substr($name, strlen($prefix) + 2);
        switch ($prefix) {
            case 'findone':
                $order = $arguments[1];
                $param_arr[0] =& $where;
                $param_arr[1] = [$where_param];
                $method = 'findonebysql';
                break;
            case 'find':
            case 'findmany':
                $order = $arguments[1];
                $param_arr[0] =& $where;
                $param_arr[1] = [$where_param];
                $method = 'findbysql';
                break;
            case 'findeach':
            case 'findeachmany':
                $order = $arguments[2];
                $param_arr[0] = $arguments[0];
                $param_arr[1] =& $where;
                $param_arr[2] = [$arguments[1]];
                $method = 'findeachbysql';
                break;
            case 'count':
            case 'delete':
                $param_arr[0] =& $where;
                $param_arr[1] = [$where_param];
                $method = "{$prefix}bysql";
                break;
            default:
                throw new BadMethodCallException("Method $class::$name not found");
        }
        if (isset($alias_fields[$field])) {
            $field = $alias_fields[$field];
        }
        if (isset($db_fields[$field])) {
            $where = "`$db_table`.`$field` IN(?) " . $order;
            return call_user_func_array([$class, $method], $param_arr);
        }
        throw new BadMethodCallException("Method $class::$name not found");
    }

    /**
     * constructor, give primary key of record as param to fetch
     * corresponding record from db if available, if not preset primary key
     * with given value. Give null to create new record
     *
     * @param mixed $id primary key of table
     */
    function __construct($id = null)
    {
        $class = get_class($this);
        //initialize configuration for subclass, only one time
        if (!array_key_exists($class, self::$config)) {
            static::configure();
        }
        //if configuration data for subclass is found, point internal properties to it
        if (self::$config[$class] !== null) {
            foreach (array_keys(self::$config[$class]) as $config_key) {
                $this->{$config_key} = self::$config[$class][$config_key];
            }
        }

        if ($id) {
            $this->setId($id);
        }
        $this->restore();
    }

    /**
     * returns internal used id value (multiple keys concatenated with _)
     *
     */
    protected function _getId($field)
    {
        return is_null($this->getId())
             ? null
             : implode(self::ID_SEPARATOR, $this->getId());
    }

    /**
     * sets internal used id value (multiple keys concatenated with _)
     * @param string $field Field to set (unused since it's always the id)
     * @param string $value Value for id field
     */
    protected function _setId($field, $value)
    {
        return $this->setId(explode(self::ID_SEPARATOR, $value));
    }

    /**
     * retrieves an additional field value from relation
     *
     * @param string $field
     * @return multitype:
     */
    protected function _getAdditionalValueFromRelation($field)
    {
        list($relation, $relation_field) = [$this->additional_fields[$field]['relation'],
                                                $this->additional_fields[$field]['relation_field']];
        if (!array_key_exists($field, $this->additional_data)) {
            $this->_setAdditionalValue($field, $this->getRelationValue($relation, $relation_field));
        }
        return $this->additional_data[$field];
    }

    /**
     * sets additional value in field imported from relation
     *
     * @param string $field
     * @param mixed $value
     * @return multitype:
     */
    protected function _setAdditionalValueFromRelation($field, $value)
    {
        list($relation, $relation_field) = [$this->additional_fields[$field]['relation'],
                $this->additional_fields[$field]['relation_field']];
        $this->$relation->$field = $value;
        unset($this->additional_data[$field]);
        return $this->_getAdditionalValueFromRelation($field);
    }

    /**
     * @param string $field
     * @return multitype:
     */
    protected function _getAdditionalValue($field)
    {
        return $this->additional_data[$field];
    }

    /**
     * @param string $field
     * @param mixed $value
     * @return multitype:
     */
    protected function _setAdditionalValue($field, $value)
    {
        return $this->additional_data[$field] = $value;
    }

    /**
     * clean up references after cloning
     *
     */
    function __clone()
    {
        //all references link still to old object => reset all aliases
        foreach ($this->alias_fields as $alias => $field) {
            if (isset($this->db_fields[$field])) {
                $content_value = $this->content[$field];
                $content_db_value = $this->content_db[$field];
                unset($this->content[$alias]);
                unset($this->content_db[$alias]);
                unset($this->content[$field]);
                unset($this->content_db[$field]);
                if (is_object($content_value)) {
                    $this->content[$field] = clone $content_value;
                } else {
                    $this->content[$field] = $content_value;
                }
                if (is_object($content_db_value)) {
                    $this->content_db[$field] = clone $content_db_value;
                } else {
                    $this->content_db[$field] = $content_db_value;
                }
                $this->content[$alias] =& $this->content[$field];
                $this->content_db[$alias] =& $this->content_db[$field];
            }
        }
        //unset all relations for now
        //TODO: maybe a deep copy of all belonging objects is more appropriate