如何在模型中避免样板代码?

时间:2012-05-16 16:24:30

标签: php codeigniter orm model

我正在使用CI,但是这个问题一般适用于模型和数据库持久性。我发现自己在以下模型中创建方法: -

private function create_joins() {
  # Add some joins to the global db object using the active record 
}

我这样做,这样我就可以为特定模型执行常见连接,而无需复制用于创建连接的代码。

所以选择方法可能是: -

public function get_by_id($id) {

    $this->db->select('some_cols');
    $this->db->from('some_table');
    $this->create_joins();
    $this->db->where(array('id' => $id));
    etc...
}

哪个好,但是我想知道这是否就像数据管理器之类的ORM可以抽象出来的那样?

2 个答案:

答案 0 :(得分:3)

您应该尝试Doctrine,这是PHP中最先进的ORM之一:

使用Doctrine,您甚至不必在模型中编写get_by_id($id)等方法:它们由Doctrine本身处理。 所以你可以写:

$entityManager->find("Bug", $id);

答案 1 :(得分:0)

另一种方法是通过php-activerecord

使用sparks

关联示例      -

class User extends ActiveRecord\Model{

    //set tablename 
    //I would advice to keep Model singular and table names plural
    //then this next step is not needed
    static $table_name = 'table_one';

    //set relationships
    static $belongs_to array(
        array('Group')
    );

    static $has_many = array(
       array('Comment'),
       array('Order')
    );

    static $has_one = array(
       array('Additional_Info')
    );

    //one key feature is callbacks
    //this helps keep controllers clean by letting you pass
    //the post data(after validation) in to modify(serialize,json_encode,calculate vat etc) 

    static $before_create = array('json_encode_my_tags');

    public function json_encode_my_tags(){
        //$this->tags === $this->input->post('tags');
        $tags = explode(',', str_replace(' ', '', $this->tags));
        return $this->tags = json_encode($tags, TRUE);
    }
}

//calling a model and using eager-loading for associations
$model = User::find(array(
    'conditions'    =>    array('id=?', $id) // PK Primary key
    'include'       =>   array('comment', 'order', 'additional_info') // eager-loading associations
)); 

$model->key;
$model->comment->key;
$model->additional_info->key;
$model->order->key;