Using DataMapper ORM for php to map field names Using DataMapper ORM for php to map field names codeigniter codeigniter

Using DataMapper ORM for php to map field names


Yes it is possible. I can explain the logic and how your can tackle the problem using a custom core class for the codeigniter application.

Create a file inside application/core/ and label it Mapdm.php

write the following inside the file.

class Mapdm {    private $map_fields = array();    function __construct($modelClass_name, $map_fields = array()){        $this->_model = new $modelClass_name(); /* instantiate Model */        $this->map_fields = $map_fields;    }    function __get($name){        if(isset($this->map_fields[$name])){            $name = $this->map_fields[$name];        }        return $this->_model->{$name};    }    function __set($name, $value){        if(isset($this->map_fields[$name])){            $name = $this->map_fields[$name];        }        return $this->_model->{$name} = $value;    }    function __call($name, $args){        return call_user_func_array(array($this->_model, $method), $args);    }}

To use this in your controller, simply instantiate this class as show below inside the controller constructor class. To simplify table field map data in the array, you may choose to store the array data inside a custom config file.

example. map_field_config.php (file contents)

$config['mapfield'][{modelname}] = array ('fieldA'=>'real_fieldname', 'fieldB'=>'real_fieldname2');

controller file setup

class ControllerName extends CI_Controller{    function __construct(){       parent::__construct();       $mapfields = $this->config->item('mapfield', $mapfields);       $model_fields = $mapfields['mymodel'];       $this->mymodel = new Mapdm('mymodel');    }    function index(){      $records = $this->mymodel->get();       } }

I have not tested this code, however I just wrote it to give you an idea. It is like creating a wrapper object for Datamapper model and calling the methods and properties using the wrapper. The wrapper should always check and return the correct table field name to the datamapper object.


You could create a view on the table, mapping fields as you require, and then use the view as your ORM class. I've used this technique with Propel where some columns required subselects that would have been too complicated to maintain the usual way, and it worked very well indeed.