Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using DataMapper ORM for php to map field names

I'm looking at using DataMapper ORM with CodeIgniter, but have a scenario where the database structure is poorly formed.

I'd like to be able to configure my model to map the database field names, to something more logical. Then, when we get around to updating the database structure, I can just update the model, and all the referencing code will continue to work.

Is this possible with DataMapper ORM?

like image 493
mattdwen Avatar asked Apr 19 '26 20:04

mattdwen


1 Answers

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.

like image 85
Raftalks Avatar answered Apr 22 '26 10:04

Raftalks