【发布时间】:2014-01-11 10:09:20
【问题描述】:
今天我尝试将我的函数转换为 PHP 类。 我尝试了一些基本步骤。
<?php
class DataBase {
private $host;
private $user;
private $password;
private $db;
private $mysqli;
function __construct() {
$this->host = "localhost";
$this->user = "root";
$this->password = "";
$this->db = "my_database";
$this->mysqli = new mysqli($this->host, $this->user, $this->password, $this->db);
}
function __destruct() {
$this->mysqli->close();
}
public function query($query, $params = '', $bind_result) {
$stmt = $this->mysqli->prepare($query);
//Need to change this to process the array of params
$stmt->bind_param('i', $params);
$stmt->execute();
//Change this to handle array of bind
$stmt->bind_result($bind_result);
//Loop the result and store it in a temp array
$stmt->fetch();
//Don't print the statement. Just close the statement and return the array.
printf("%s\n", $bind_result);
/* close statement */
$stmt->close();
}
}
?>
我现在必须创建另一个类。我在数据库中创建了一个虚拟表。
<?php
class Dummy {
private $database;
function __construct() {
$this->database = new Database();
}
public function getAllDummy() {
$query = "SELECT name FROM dummy WHERE id = ?";
$this->database->query($query, 1, 'name');
}
}
?>
但我认为这不是做事的正确方法。我觉得有些方法是正确的,有些方法是错误的。
当我调用 query() 函数时,我需要在每个类的构造方法中一直连接数据库吗?或者我需要将数据库类更改为静态函数吗?所以我可以调用诸如 Database::query(); 之类的函数;
看来我需要从一开始就创建所有内容。这样的模型是否已经在互联网上可用?比如cakephp、codeigniter
【问题讨论】:
-
您可以在其他类中使用诸如
__construct(Database $db)之类的“依赖注入”;要使用多个参数进行查询,请查看this comment。这里有些人会建议使用 PDO 以获得更“流畅”的界面。