【问题标题】:Difficulty using array in object oriented programming in php [closed]在php中的面向对象编程中使用数组的困难[关闭]
【发布时间】:2015-01-22 12:07:07
【问题描述】:

我想根据多个条件从 MySQL 数据库中提取数据,但我的操作函数只允许我根据 1 个条件提取数据。

请帮我修改动作函数,以便我可以使用多个数组来提取数据。

public function query($sql, $params = array()) {
    $this->error = false;
    if ($this->query = $this->pdo->prepare($sql)) {
        $x = 1;
        if (count($params)) {
            foreach ($params as $param) {
                $this->query->bindValue($x, $param);
                $x++;
            }
        }
        if ($this->query->execute()) {
            $this->results = $this->query->fetchAll(PDO::FETCH_OBJ);
            $this->count = $this->query->rowCount();
        } else {
            $this->error = true;
        }
    }
    return $this;
}

public function action($action, $table, $where = array()) {
    if (count($where === 3)) {
        $operators = array('=', '>', '<', '>=', '<=');

        $field = $where[0];
        $operator = $where[1];
        $value = $where[2];

        if (in_array($operator, $operators)) {
            $sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";

            if (!$this->query($sql, array($value))->error()) {
                return $this;
            }
        }
    }
    return false;
}

public function get($table, $where) {
    return $this->action('SELECT *', $table, $where);
}

【问题讨论】:

  • 这是你能想到的最糟糕的数据库抽象层设计。 action?当您尝试使用 update 时,祝您好运。

标签: php mysql arrays oop


【解决方案1】:

在面向对象的 ORM 层中,通常有一个单独的类用于语句,或者更具体地说,对于 SELECT 语句,例如

$users = $db->select('*')
   ->from('users')
   ->where('id', '>', 100)
   ->where('name', 'like', 'agg%')
   ->orderBy('name')
   ->execute()
   ->getResults();

设计一个允许这样的类的课程将是一个很好的学习练习。

【讨论】:

  • 我是 OOP 新手,能否请您帮我详细说明一下您的回答,以便我理解它
  • @aggarwal:这叫做"fluent interface"。基本上,您创建一个对象并使用方法来设置其属性。每个这样的方法都返回$this,从而允许进一步的链接。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多