1

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

4

2 回答 2

3

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

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

$entityManager->find("Bug", $id);
于 2012-05-16T16:50:12.910 回答
0

另一种方法是通过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;
于 2012-05-17T21:07:32.137 回答