我遵循MVC OOP结构,我想知道一个像样的数据库类会是什么样子。数据库类的目的是让其他类调用或扩展它的方法。
这就是我的连接.php现在的样子
<?php
$db = new mysqli('localhost', 'root', '', 'audiologiska_kliniken');
if($db->connect_errno > 0){
die('Ett fel inträffade [' . $db->connect_error . ']');
}
这是我开始的数据库类。
<?php
include 'C:/wamp/www/mvc/include/connect.php';
class Database
{
private $host;
private $user;
private $password;
private $database;
function __construct{
// if(file_exists($filename)) {include '';}
//else throw new exception("Error!");
$this->host=$host;
$this->user=$user;
$this->password=$password;
$this->database=$database;
$this->connect();
}
private function connect()
{//Connect to the server
if(!mysqli_connect($this->host, $this->user, $this->password, $this->database))
我知道它看起来不太好,但我真的不知道如何进一步改进它。我将不胜感激你们的一些建议
正如 Halcyon 所提到的,研究使用命名空间、作曲家或您自己的 spl_autoload 函数进行自动加载。
您还应该对其他设计模式进行一些调查。
通常使用单一实例模式来防止每个请求/响应周期加载多个数据库连接。
这样,每次您需要数据库连接时,都可以执行以下操作:
$db = DB::getInstance();
如果以前没有创建类或现有连接,这将返回连接的新实例。
通过实现__cloned魔术方法,阻止实例被人们克隆也可能是一个好主意:
public function __clone() {
throw new Exception("Can't clone a singleton");
}
然而,人们认为单例是不好的,因为它们在应用程序中引入了全局状态和紧密耦合。这使得它们难以测试。另一种方法是考虑使用服务,这是
应用程序中的全局内容。http://fabien.potencier.org/article/11/what-is-dependency-injection Symfony有一个很好的方法来使用服务和依赖注入容器。
Laravel在IoC容器中也有一个很好的依赖注入容器的例子。它是管理类解析的单个类。该框架调用其服务提供者。
像这样工作有很多优点,例如易于测试和应用程序中对象之间的松散耦合。
https://github.com/illuminate/database 特别是 Connection.php 和 ConnectionResolver.php 是实现数据库连接的一种方法。Connection.php 表示实际连接,每次使用工厂模式创建该连接,并且 ConnectionResolver 足够智能,可以处理多个连接。寻找灵感:)