简体   繁体   中英

PHP OOP and PDO

My first real foray into using PHP OOP and PDO extensively. I have finally gotten the script to work, but as you notice in order to do it I had to move the PDO connect into the login function - originally it was just in the __construct() . I do not want to have to open a new PDO connect and this is sloppy. How can I maintain the same connection throughout the whole class?

 <?php
class user{

public $id;
public $name;
public $email;
private $password;

public function __construct() {
    $DBH = new PDO("mysql:host=HOST;dbname=DB", "USER", "PASS");  
    $DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}

public function login($email,$password,$type){

    $DBH = new PDO("mysql:host=HOST;dbname=DB", "USER", "PASS");  
    $DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $password_hash = sha1($password);
    try{
        if ($type != "actives") {
            throw new Exception("Type Handling Error");
        }
        $STH = $DBH->query("SELECT id, email, password FROM $type WHERE email='$email' AND password='$password_hash'");
        $STH->setFetchMode(PDO::FETCH_ASSOC);  
        $row_count = $STH->rowCount();  
        $row = $STH->fetch();

        if($row_count == 1){
            session_start();
            session_regenerate_id();
            $_SESSION['id'] == $row[id];
            return true;
        }
        else{
        return false;
        }
    }
    catch (Exception $e) {
        echo $e->getMessage();
    }

}

public function loggout(){
    session_destroy();
    setcookie(session_name(), session_id(), 1, '/');
}

Make the database handle a private member within the class:

class user
{    
    public $id;
    public $name;
    public $email;
    private $password;
    private $dbh;

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

    public function login($email, $password, $type)
    {
        $dbh = $this->dbh;
        ...
    }

Usage:

$pdo = new PDO("mysql:host=HOST;dbname=DB", "USER", "PASS");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$user = new User($pdo);

Sooner or later, you may need the PDO connection object somewhere else in your code(outside your user object). Therefore, I would suggest to use one class which will provide static method as below to get the PDO connection object everywhere you want.

             class Database{
                    private static $datasource='mysql:host=HOST dbname=DB';
                    private static $username='USER';
                    private static $password='PASS';
                    private static $db;

                    //make the constructor private and empty so that no code will create an object of this class.
                    private function __construct(){}

                     //the main public function which will return the required PDO object
                     public static function getDB(){
                      if(!isset(self::$db)){
                           try{
                         self::$db=new PDO(self::$datasoure,self::$username,self::$password);

                            }
                            catch(PDOExceptin $e)
                            {
                               $error=$e->getMessage(); //variable $error can be used in the database_error.php file 
                               //display database error file.
                               include('database_error.php');
                               exit();
                            }
                      }
                        return self::$db; 
                     }

                    }

Then you can use the static method like below any time you want PDO connection

                    $conn=Database::getDB();

Use ceejayoz' proposal or add a global function which is responsible for establishing the database connection. The function is written as to connect to the database at most 1 time per HTTP request:

function getPDOConnection() {
    // Thanks to the static-specifier, this variable will be initialized only once.
    static $conn = new PDO("mysql:host=HOST;dbname=DB", "USER", "PASS");

    return $conn;
}

This enables you to maintain the same connection in your whole application (but of course you don't have to use the function everywhere). Basically, this is a very simple application of the Singleton pattern. See the documentation of the static specifier/keyword and try to get familiar with the Singleton pattern .

将数据库连接添加为构造函数中的参数,因此当您从用户类创建新实例时,它会自动在实例化对象中运行

The variable $DBH needs to be a member variable of your class.

Below private $password; , add private $DBH; and you're good to go with deleting the new-connection code from your login function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM