替代在类中使用全局变量?

时间:2012-06-30 16:59:32

标签: php database oop class pdo

我已经开始学习如何使用OOP并创建了一个用户授权类来检查用户是否存在等。目前我使用全局变量$dbh连接到数据库,这是一个PDO连接。我听说以这种方式使用全局变量并不是一种好的做法,但我不确定如何改进它,我是否只需将$dbh变量传递给连接数据库时需要它的方法以及为什么这究竟是不是好的做法?

以下是我正在使用的一些代码:

调用程序中包含的数据库PDO连接:

//test the connection
    try{
        //connect to the database
        $dbh = new PDO("mysql:host=localhost;dbname=oopforum","root", "usbw");

    //if there is an error catch it here
    } catch( PDOException $e ) {
        //display the error
        echo $e->getMessage();
    }

需要数据库连接的类:

class Auth{

        private $dbh;

        function __construct(){

            global $dbh;
            $this->dbh = $dbh;
        }

        function validateLogin($username, $password){

            // create query (placing inside if statement for error handling)
            if($stmt = $this->dbh->prepare("SELECT * FROM oopforumusers WHERE username = ? AND password = ?")){

                $stmt->bind_param(1, $username);
                $stmt->bind_param(2, $password);
                $stmt->execute();


                // Check rows returned
                $numrows = $stmt->rowCount();

                //if there is a match continue
                if( $numrows > 0 ){
                    $stmt->close();
                    return TRUE;
                }else{
                    $stmt->close();
                    return FALSE;
                }

            }else{
                die('ERROR: Could not prepare statement');
            }

        }


        function checkLoginStatus(){

            if(isset($_SESSION['loggedin'])){

                return TRUE;

            }else{

                return FALSE;

            }

        }

        function logout(){

            session_destroy();
            session_start();

        }
    }

3 个答案:

答案 0 :(得分:6)

您应该将PDO连接传递给构造函数:

function __construct($dbh) {
    $this->dbh = $dbh;
}

这个连接被称为你的类的依赖,因为显然你的类需要它来执行它的功能。好的做法要求你的类应该使显式表明这种依赖存在;这是通过使其成为必需的构造函数参数来实现的。

如果您从全局变量中提取依赖项,则会产生以下几个问题:

  • 本课程的用户根本不清楚首先是依赖
  • 您的类现在已耦合到全局变量,这意味着在不破坏程序的情况下无法删除或重命名该变量
  • 您已经为“远距离操作”创建了前提条件:修改全局变量的值会导致应用程序中另一个(看似无关的)部分改变行为

答案 1 :(得分:2)

您只需将其传递给构造函数即可。

function __construct($connection){
         $this->connection = $connection;
}

创建对象时,您可以:

$obj = new Class($dbh);

答案 2 :(得分:2)

通过构造函数传递数据库对象。 PHP的对象模型意味着=创建对同一对象实例的新引用。

class ThingThatDependsOnDatabase
{
    private $db = NULL;

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

    public function selectSomething ($id)
    {
        $sql = 'SELECT * FROM table WHERE id = ?;'
        $this -> db -> prepare ($sql);
        // And so on
    }
}

这是一个名为Dependency Injection的模式的示例,因为您的类依赖的东西是通过方法(setter,constructor等)注入的。

相关问题