开发者

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 th开发者_开发百科e referencing code will continue to work.

Is this possible with DataMapper ORM?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜