我通过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) 我听过"脂肪模型,瘦控制器"这个短语,相信我理解它的含义.在完成Zend快速入门指南时,我遇到了表数据网关模式.
在我看来,这种设计模式是提倡MVC堆栈的第四个组件.它正在从"胖模型"转变为"瘦模型,瘦控制器和胖胖的TableDataGateway".根据我对这种设计模式的理解,模型变得只是TableDataGateway填充数据的存储机制.
我理解表数据网关设计模式的优点,抽象我们的数据源,我的问题不是关于设计模式,而是它如何适应MVC堆栈.
PS我有点难以将问题变成好话.如果有人想编辑它以使其更清楚或提出建议我是开放的!