【问题标题】:How to avoid boilerplate code in my models?如何在我的模型中避免样板代码?
【发布时间】:2012-05-16 16:24:30
【问题描述】:

我正在使用 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 可以抽象掉的那种东西?

【问题讨论】:

    标签: php codeigniter orm model


    【解决方案1】:

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

    使用 Doctrine,您甚至不必在模型中编写诸如 get_by_id($id) 之类的方法:它们由 Doctrine 自己处理。 所以你可以写:

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

    【讨论】:

    【解决方案2】:

    另一种方法是通过sparks 使用php-activerecord

    关联示例 -

    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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-22
      • 1970-01-01
      • 2015-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多