在我开始在我的项目中实现以下内容之前,我正在尝试创建一个简单的示例类,我想知道是否有一些我可以/应该改进的地方。如果有人给我一些关于我现在做得如何的意见,我会很高兴。
简单的类示例:
// 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;
}
这只是我想如何使用它的一个基本示例。你觉得我应该改进什么?