【问题标题】:Codeigniter - Creating own helperCodeigniter - 创建自己的助手
【发布时间】:2012-03-06 17:37:10
【问题描述】:

我尝试创建自己的助手。 首先,我创建了一个名为 HelperModelBase 的文件。

这是一个抽象类。

abstract class Pasaj_Model_Base {

    public $table_name;
    public $table_alias;
    public $class_name;
    public $lastSql;

    public function __construct() {
        $this->class_name = get_class($this);
        $this->table_name = strtolower($this->class_name);
        $this->table_name = str_replace('_dbview', '', $this->table_name);
    }

并创建一个名为 select 的方法

public function select($where = null, $order = null, $limit = null, $columns = '*') {
        if (!$columns)
            $this->db->select('*');
        elseif (is_array($columns)) {
            $columns = implode(',', $columns);
            $this->db->select($columns);
        }



}

正如您在上面看到的,我做了一个简单的选择操作,但是,我想做的是添加一个或多个操作。

例如 where 和 order by 为了做到这一点。我将此添加到我的方法中:

if($where)

问题从这里开始,因为 codeigniter 有一个特殊的代码来处理 where 操作。

$this->db->where();

我该怎么做?我怎么能在我的情况下

$this->db->select();

谢谢。

我终于来了。

public function select($where = null, $order = null, $limit = null, $columns = '*') {
        if (!$columns)
            $this->db->select('*');
        elseif (is_array($columns)) {
            $columns = implode(',', $columns);
            $this->db->select($columns);
        }

        if($where) 
            $this->db->where($where);
        if($order)
            $this->db->order_by($order);
        if($limit)
            $this->db->limit($limit);

        $query = $this->db->get();

        return $query;
    }

我会注意到参数的语法。上面的代码可以运行吗?

【问题讨论】:

  • 通常您对数据库的调用是在模型中,而不是在助手中。此外,当它不是 null 时,你的 where 包含什么?
  • 将您的查询移动到模型中,并创建操作这些数据的方法。
  • 我知道这毫无意义,但不幸的是我的老板想要这样:@
  • 如何根据 where、order by 子句的存在创建不同的方法?然后,在控制器类中,放置条件并从控制器中的助手调用适当的方法?听起来很难看,但它可能会对你有所帮助。
  • 您的老板是否明确说过“让我成为一个覆盖 HELPER 中的数据库驱动程序的抽象类,否则您会被解雇”,或者您可以欺骗创建这个类,但它应该最适合哪里?跨度>

标签: php codeigniter


【解决方案1】:

建议你看看

CodeIgniter User Guide : Models

使用 CodeIgniter,对数据库的调用是在模型中进行的,而不是在帮助程序中。

然后,如果您的 $where 是一个关联数组(事实上,如果我很好地阅读了您的代码,它必须这样做),您可以执行 foreach 循环来分配 where 子句和值。

【讨论】:

    猜你喜欢
    • 2010-10-22
    • 2011-12-17
    • 2013-04-04
    • 2011-03-09
    • 1970-01-01
    • 1970-01-01
    • 2014-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多