我通过PDO访问我的MySQL数据库.我正在设置对数据库的访问权限,我的第一次尝试是使用以下内容:
我想到的第一件事是global:
$db = new PDO('mysql:host=127.0.0.1;dbname=toto', 'root', 'pwd');
function some_function() {
global $db;
$db->query('...');
}
Run Code Online (Sandbox Code Playgroud)
这被认为是一种不好的做法.一点点搜索后,我结束了与Singleton模式,其
"适用于需要单个类实例的情况."
根据手册中的示例,我们应该这样做:
class Database {
private static $instance, $db;
private function __construct(){}
static function singleton() {
if(!isset(self::$instance))
self::$instance = new __CLASS__;
return self:$instance;
}
function get() {
if(!isset(self::$db))
self::$db = new PDO('mysql:host=127.0.0.1;dbname=toto', 'user', 'pwd')
return self::$db;
}
}
function some_function() {
$db = Database::singleton();
$db->get()->query('...');
}
some_function();
Run Code Online (Sandbox Code Playgroud)
当我能做到这一点时,为什么我需要相对较大的课程呢?
class Database {
private static $db;
private function __construct(){}
static function get() …Run Code Online (Sandbox Code Playgroud) 我不时会看到有关连接数据库的问题.
大多数答案不是我这样做的方式,或者我可能没有正确得到答案.无论如何; 我从来没有想过这个,因为我这样做对我有用.
但这是一个疯狂的想法; 也许我这样做是错的,如果是这样的话; 我真的想知道如何使用PHP和PDO正确连接到MySQL数据库并使其易于访问.
我是这样做的:
首先,这是我的文件结构(剥离):
public_html/
* index.php
* initialize/
-- load.initialize.php
-- configure.php
-- sessions.php
Run Code Online (Sandbox Code Playgroud)
index.php
在最顶端,我有require('initialize/load.initialize.php');.
load.initialize.php
# site configurations
require('configure.php');
# connect to database
require('root/somewhere/connect.php'); // this file is placed outside of public_html for better security.
# include classes
foreach (glob('assets/classes/*.class.php') as $class_filename){
include($class_filename);
}
# include functions
foreach (glob('assets/functions/*.func.php') as $func_filename){
include($func_filename);
}
# handle sessions
require('sessions.php');
Run Code Online (Sandbox Code Playgroud)
我知道有更好或更正确的方法来包含类,但不记得它是什么.还没有时间去研究它,但我认为这是有道理的autoload.类似的东西......
configure.php
这里我基本上只是覆盖一些php.ini -properties并为该站点做一些其他的全局配置
connect.php
我把连接放到一个类上,所以其他类可以扩展这个...
class …Run Code Online (Sandbox Code Playgroud) /* 连接文件 */
class dbconnect{
public function connect(){
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'demo';
$connection = mysqli_connect($host,$user,$pass,$db);
return $connection;
}
}
Run Code Online (Sandbox Code Playgroud)
/* dao 文件 */
include 'dbconnect.php';
class dao extends dbconnect{
private $conn;
function __dao(){
$dbcon = new dbconnect();
$conn = $dbcon->connect();
}
function select( $table , $where='' , $other='' ){
if(!$where = '' ){
$where = 'where' . $where;
}
$sele = mysqli_query($this->conn,"SELECT * FROM $table $where $other") or die(mysqli_error($this->conn));
echo $sele;
return …Run Code Online (Sandbox Code Playgroud)