[英]PHP and Mysqli OOP - Handling database
今天我试图将我的函数转换为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类更改为静态函数吗? 所以我可以调用Database :: query()等函数;
我似乎需要从一开始就创造一切。 互联网上是否已有此类型号? 像cakephp,codeigniter
我想建议你阅读有关PHP的ORM的一些内容。 例如我使用Doctrine 2( http://www.doctrine-project.org/ )它有点复杂,但绝对值得学习。 您尝试编码的所有内容已经完成,那么为什么要重新编写代码呢?
在你的OOP原则中有一些错误。
除了Doctrine(它已经强大且全能,但仍然很复杂)我可以建议你db.php( http://dbphp.net )做什么教条,但是单个文件,并且非常容易使用。 缺点:它还没有很好的文档记录,还没有大的社区。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.