PHP PDO类设计 [英] PHP PDO Class Design

查看:123
本文介绍了PHP PDO类设计的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的PDO数据库访问类的以下类设计。

I have the following class design for my PDO database access class.

$ conn = new db()的最佳位置在哪里? (目前在Database.php中)?
记住一个MVC风格框架,Main.php是控制器,另外两个是模型。

Where is the best location for $conn = new db(); (currently within Database.php)? Keeping in mind an MVC style framework, with Main.php being the controller, and the other two being Models.

谢谢。

Database.php

class db {
    private $conn;

    public function __construct() {
        $this->conn = new PDO(...);
    }

    $conn = new db();
}

Class.php
$ b

Class.php

// require Database.php

class someClass {
    private $conn;

    public function __construct(db $conn) {
        $this->conn = $conn;
    }

    function myFunc($usr, $pwd) { 
        // SQL
    } 
}

Main.php

// require Class.php
$myObj = new someClass($conn);

$myObj->myFunc(PARAMS);


推荐答案

$ conn 需要在 someClass 定义之外并在实例化 someclass 之前声明。所以,我可以想到两个选项:

As you can tell, $conn needs to be declared outside of the someClass definition and before you instantiate someclass. So, there are two options that I can think of:

在创建 $ myObj 对象之前声明它传递给构造函数:

Declare it before you create the $myObj object and pass it to the constructor:

 $conn = new db();
 $myObj = new someClass($conn);

或者,使用 db 中的 singleton设计模式

 $conn = db::getInstance();
 $myObj = new someClass($conn);

其中 db :: getInstance()定义为:

class db {
    private $conn;

    // Don't let anyone instantiate this class by themselves
    private function __construct() {
        $this->conn = new PDO(...);
    }

    private static $instance = null;
    public static getInstance() {
        if( self::$instance === null) {
            self::$instance = new db();
        } 
        return self::$instance;
    }
}

这篇关于PHP PDO类设计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆