我想創建一個簡單的示例類,然後開始在項目中實現以下內容,並且想知道是否有某些我可以/應該改進的東西。如果有人給我一些我現在正在做的事情,我會很高興。面向對象的PHP + PDO - 這是應該如何?
簡單類的例子:
// define class
class User{
private $UserID;
private $UserName;
private $Email;
function SetUserID($NewUserID){
$this -> UserID = $NewUserID;
}
function GetUserID(){
return $this -> UserID;
}
function SetUserName($NewUserName){
// update object
$this -> UserName = $NewUserName;
}
function GetUserName(){
return $this -> UserName;
}
function SetEmail($NewEmail){
$this -> Email = $NewEmail;
}
function GetEmail(){
return $this -> Email;
}
public function SaveUser(){
// check if user exists
$User = new User();
if ($User->UserExists($this->UserID)){
// user exists - update him
$Pdo = new PDO('mysql:host=localhost;dbname=cms;charset=utf8', 'xxx', 'xxx');
$Query = $Pdo->prepare("Update User set UserName = :UserName, Email = :Email, UserID = :UserID where UserID = :UserID");
$Query->bindValue(':UserName', $this->UserName);
$Query->bindValue(':Email', $this->Email);
$Query->bindValue('UserID', $this->UserID);
$Query->execute();
$Pro = null;
}
else{
// insert new
$Pdo = new PDO('mysql:host=localhost;dbname=cms;charset=utf8', 'xxx', 'xxx');
$Query = $Pdo->prepare("Insert into User (UserName, Email) values (:UserName, :Email)");
$Query->bindValue(':UserName', $this->UserName);
$Query->bindValue(':Email', $this->Email);
$Query->execute();
// close connection
$Pdo = null;
}
}
private function UserExists($UserID){
// returns true if users exists, false if not
$Pdo = new PDO('mysql:host=localhost;dbname=cms;charset=utf8', 'root', 'vertrigo');
$Query = $Pdo->prepare("SELECT * FROM User WHERE UserID=:UserID");
$Query->bindValue(':UserID', $UserID);
$Query->execute();
$Row = $Query->fetch(PDO::FETCH_ASSOC);
$Pdo = null;
// get user
if ($Row){
return true;
}
else{
return false;
}
}
}
function GetUserInfo($UserID){
// open pdo
$Pdo = new PDO('mysql:host=localhost;dbname=cms;charset=utf8', 'root', 'vertrigo');
$Query = $Pdo->prepare("SELECT * FROM User WHERE UserID=:UserID");
$Query->bindValue(':UserID', $UserID);
$Query->execute();
$Row = $Query->fetch(PDO::FETCH_ASSOC);
$Pdo = null;
// get UserInfo
$UserInfo = new User();
$UserInfo -> SetUserID($UserID);
$UserInfo -> SetUserName($Row["UserName"]);
$UserInfo -> SetEmail($Row["Email"]);
// return UserInfo
return $UserInfo;
}
這是我想如何與它的工作只是一個簡單的例子。你認爲我應該改進什麼?
只是好奇,你是否嘗試瀏覽其他類似的問題? –
這更適合[programmers.stackexchange.com](http://programmers.stackexchange.com/),它是一般代碼改進問題。 –
你正在改變數據庫密碼真的很難... –