代码之家  ›  专栏  ›  技术社区  ›  stormdrain

在codeigniter中将参数和条件传递给模型

  •  0
  • stormdrain  · 技术社区  · 16 年前

    我正在给一个项目添加一些模型,想知道是否有一种“最佳实践”的方法来创建模型:

    为每个特定查询创建函数有意义吗?

    我开始这样做,然后有了创建一个泛型函数的想法,我可以传递参数给。例如:

    而不是

    function getClients(){
        return $this->db->query('SELECT client_id,last FROM Names ORDER BY id DESC');
        }
        function getClientNames($clid){
            return $this->db->query('SELECT * FROM Names WHERE client_id = '.$clid);
        }
        function getClientName($nameID){
            return $this->db->query('SELECT * FROM Names WHERE id ='.$nameID);
        }
    }
    

    有点像

    function getNameData($args,$cond){
        if($cond==''){
            $q=$this->db->query('SELECT '.$args.' FROM Names');
            return $q;
        }else{
            $q=$this->db->query('SELECT '.$args.' FROM Names WHERE '.$cond);
            return $q;
        }
    }
    

    我可以将字段和条件(如果适用)传递给模型。后一个例子是不是有什么不好的原因?

    谢谢!

    1 回复  |  直到 16 年前
        1
  •  0
  •   bschaeffer    16 年前

    我认为使用ci的活动记录来编译查询实际上是一个更好的主意。

    一个例子:

    function all_clients($select)
    {
        $this->db->select($select);
    
        return $this->_get_client_data();
    }
    
    function single_client($select, $id = "")
    {
        // validate $id
    
        $this->db->select($select);
        $this->db->where("id", $id);
        $this->db->limit(1);
    
        return $this->_get_client_data();
    }
    
    // Only called by a method above once the query parameters have been set.
    
    private function _get_client_data()
    {
        $q = $this->db->get("clients");
    
        if($q->num_rows() > 0)
        {
            return $q->result_array();
        }
    
        return FALSE;
    }
    

    ci的活跃记录让你想做的事情变得简单多了。可以想象在实际调用之前设置公共函数来有条件地设置许多选项 $this->db->get() .

    我想你会打电话 _get_client_data 一网打尽(?)通过一个方法运行所有的数据检索,使得错误处理这样的事情更容易维护。

    注意:永远记住这样验证数据。我知道你知道,但我只是重复。