2011-01-06 97 views
1

我正在爲我的公司項目編寫數據庫api。高級的oop概念

我們在數據庫API中有4個類。

  1. 用戶類(包括關於用戶信息)
  2. 凹形板類(包括GIB信息)
  3. 卡類(
    1. 每個用戶擁有一個卡
    2. 每個用戶擁有兩個扁栓卡
    3. 一個用戶可以給其他用戶任何卡用戶卡或gib卡。
  4. 連接
    1. 可以有許多用戶卡或gib卡的連接,特別是gib。
  5. 用於製作數據庫查詢的db類。

此頁面,在這裏我打電話的類

<?php 
include_once "config.php"; 
foreach($_REQUEST as $key=>$value){ 
    $$key=$value; 
} 

if($pagelength=='')$pagelength=10;// default page length 
//because by username can update the other users data 
if($username!='' && $command!='saveuser'){ 
    $user=User::getuserarray($username); 
    $userid=$user['userid']; 
} 
if($isowner!=''){ 
    $user=User::getuserarray($isowner); 
    $userid=$user['userid']; 
} 
$users = array (
    "userid" => $userid, 
    "username" => $username, 
    "firstname" => $firstname, 
    "lastname" => $lastname, 
    "password" => $password, 
    "email" => $email, 
    "photo" => '', 
    "url" => $url, 
    "avatar_url" => $avatar_url, 
    "thumb" => $thumb, 
    "crop_url" => $crop_url, 
    "crop_position" => $crop_position 
); 
$getcard=array(
    'cardid'=>$cardid, 
    'card_type'=>$card_type, 
    'status'=>$status, 
    'userid'=>$userid, 
    'userid_to'=>$userid_to, 
    'message'=>$message, 
    'name'=>$name, 
    'pagelength'=>$pagelength, 
    'pagenumber'=>$pagenumber, 
    'fields'=>$fields 
); 
$getuser=array(
    'userid'=>$userid, 
    'name'=>$name, 
    'pagelength'=>$pagelength, 
    'pagenumber'=>$pagenumber, 
    'fields'=>$fields 

); 
$getgib=array(
    'gibid'=>$gibid, 
    'userid'=>$userid, 
    'isowner'=>$isowner, 
    'description'=>$description, 
    'tagline'=>$tagline, 
    'name'=>$name, 
    'pagelength'=>$pagelength, 
    'pagenumber'=>$pagenumber, 
    'fields'=>$fields 
); 
$getlink=array(
    'gibid'=>$gibid, 
    'view'=>$view, 
    'userid'=>$userid, 
    'cardid'=>$cardid, 
    'name'=>$name, 
    'pagelength'=>$pagelength, 
    'pagenumber'=>$pagenumber, 
    'fields'=>$fields 
); 
switch($command){ 
    case 'login': 
     $user=new User(array()); 
     $msg=$user->login($username,$password); 
     break; 
    case 'logout': 
     $user=new User(array('userid'=>$userid)); 
     $user->logout($id_session); 
     break; 
    //~ case 'isowner': 
     //~ $gib=new Gib(array('gibid'=>$gibid)); 
     //~ $user=new User(array('userid'=>$userid)); 
     //~ if($user->validateUserid()!=true) return $msg; 
     //~ if($gib->validateGibid()!=true) return $msg; 
     //~ $msg=$gib->isowner($userid,$gibid); 
     //~ break; 
    case 'saveuser': 
     $user=new User($users); 
     if($userid==''){ 
      //checking if blank fields 
      $msg=$user->validate(); 
      if($msg!='ok')break; 
      $msg=$user->adduser(); 
     }else{ 
      $msg=$user->updateuser(); 
     } 
     break; 
    //~ case 'updateuser': 
     //~ $user=new User($users); 
     //~ $user->updateuser(); 
     //~ break; 
    case 'changepassword': 
     $user=new User($users); 
     $msg=$user->changepassword($old_pswd,$new_pswd,$confirm_pswd); 
     break; 
    case 'changeimage': 
     $user=new User($users); 
     $user->changeimage($thumb,$url,$avatar_url,$crop_position,$crop_url); 
     break; 

    case 'getuser': 
     $user=new User(array('userid'=>$userid)); 
     $msg=$user->getuser($getuser); 
     break; 
    /*----------link command -----------*/ 
    case 'getlink': 
     $connection=new Connection(array()); 

     $connections=$connection->getlink($getlink); 
     $connections=array('links'=>$connections); 
     echo $msg=json_encode($connections); 
     break; 
    case 'createlink': 
     $user=new User($users); 
     $msg=$user->validateUserid(); 
     if($msg!='ok') break; 
     $connection=new Connection(array()); 
     $msg=$connection->createlink($getlink); 
     break; 
    case 'updatelink': 
     $connection=new Connection(array('linkid'=>$linkid)); 
     $msg=$connection->validate(); 
     if($msg!='ok')break; 
     $connection->updatelinkposition($positionx,$positiony); 
     break; 
    case 'deletelink': 
     $connection=new Connection(array('linkid'=>$linkid)); 
     $msg=$connection->validate(); 
     if($msg!='ok')break; 
     $connection->deletelink(); 
     break; 
    //~ case 'cardsend_validate': 
     //~ $card=new Card(array('cardid'=>$cardid)); 
     //~ $msg=$card->cardSendValidate($userid_to); 
     //~ break; 
    case 'getcard': 
     $card=new Card(array('cardid'=>$cardid)); 
     $cards=$card->getcardlist($getcard); 
     if($cardid=='') 
      echo $msg=$cards; 
     else 
      echo $msg=json_encode($cards); 
     break; 
    case 'givecard': 
     $card=new Card(array('cardid'=>$cardid)); 
     $msg=$card->validate(); 
     if($msg!='ok')break; 
     $user=new User(array('userid'=>$userid_to)); 
     $msg=$user->validateUserid(); 
     if($msg!='ok') break; 
     $msg=$card->givecard($getcard); 
     break; 
    case 'cardar'://accept reject 
     $card=new Card(array('cardid'=>$cardid)); 
     $msg=$card->validate(); 
     if($msg!='ok')break; 
     $msg=$card->acceptReject($getcard); 
     break; 
    case 'deletecard': 
     $card=new Card(array('cardid'=>$cardid)); 
     $msg=$card->validate(); 
     if($msg!='ok')break; 
     $msg=$card->delete_card(); 
     break; 
    case 'getgib': 
     $gib=new Gib(array('gibid'=>$gibid)); 
     $gibs=array('success'=>true,'gibs'=>$gib->getgibs($getgib)); 
     echo $msg=json_encode($gibs); 
     break; 
    case 'savegib': 
     $gib=new Gib(array('gibid'=>$gibid)); 
     $user=new User($users); 
     $msg=$user->validateUserid(); 
     if($msg!='ok') break; 
     if($gibid==''){ 
      $gibA=$gib->creategib($name,$type,$userid,$description,$tagline,$gib_background); 
      $gibid=$gibA['gibid']; 
      $gib->gibid=$gibid; 
      $msg= 'gib created Successfully'; 
     }else{ 
      $gib->updategib($name,$description,$tagline,$gib_background); 
      $msg= 'update Form submission complete'; 
     } 
     $arrayjson1=array(
      'success' => true, 
      'message'=>$msg 
     ); 
     $gibA=$gib->getDetail(); 
     echo $msg= formjson(array(),$gibA,$arrayjson1); 
     break; 


    default: 
     break; 
} 

?> 

<script language="javascript"> 
window.location.href="enterspace.php?msg=<?php echo urlencode($msg); ?>"; 
</script> 

我在這裏只顯示你的建議的用戶類中的方法

<?php 
Class User{ 

    var $userid; 
    var $username; 
    var $firstname; 
    var $password; 
    var $email; 
    var $photo; 
    var $avatar; 
    var $thumbnail; 
    var $crop_url; 
    var $crop_position; 



    function User($users){ 
     $this->userid=$users['userid']; 
     $this->username= $users['username']; 
     $this->firstname=$users['firstname']; 
     $this->lastname=$users['lastname']; 
     $this->password= $users['password']; 
     $this->email=$users['email']; 
     $this->photo= $users['photo']; 
     $this->avatar= $users['avatar']; 
     $this->thumbnail= $users['thumbnail']; 
     $this->crop_url= $users['crop_url']; 
     $this->crop_position= $users['crop_position']; 

    } 
    function validateUserid(){ 
     if($this->userid==''){ 
      $msg=geterrormsg(1); 
      $arrayjson1=array(
         'success' => false, 
         'message'=>$msg, 
         'error_code'=>'1'); 
      echo $msg= formjson(array(),array(),$arrayjson1); 
      return $msg; 

     } 
     $sql="select count(*) from users where userid=?"; 
     $count=Db::getValue($sql,$this->userid); 
     //User not exist 
     if($count<=0){ 
      $msg=geterrormsg(1); 
      $arrayjson1=array(
         'success' => false, 
         'message'=>$msg, 
         'error_code'=>'1'); 
      echo $msg= formjson(array(),array(),$arrayjson1); 
      return $msg; 
     } 
     return 'ok'; 

    } 

    function validate(){ 
     //checking if blank fields 
     if($this->firstname=='' or $this->lastname=='' or $this->password=='' or $this->email=='' or $this->username==''){ 
      $msg=geterrormsg(6); 
      $arrayjson1=array(
         'success' => false, 
         'message'=>$msg, 
         'error_code'=>'6' 
        ); 
      echo $msg= formjson(array(),array(),$arrayjson1); 
      return false; 
     } 
     if($this->userid==''){ 
      $totalUsers = Db::getValue('SELECT COUNT(username) FROM users where username = ?',$this->username); 
      if($totalUsers>0){ 
       //username already exist 
       $msg=geterrormsg(5); 
       $arrayjson1=array(
         'success' => false, 
         'message'=>$msg, 
         'error_code'=>'6' 
        ); 
       echo $msg= formjson(array(),array(),$arrayjson1); 
       return $msg; 
      } 
      $totalUsers = Db::getValue('SELECT COUNT(email) FROM users where email = ?',$this->email); 
      if($totalUsers>0){ 
       $msg=geterrormsg(4); 
        //email already exist 
       $arrayjson1=array(
         'success' => false, 
         'message'=>$msg, 
         'error_code'=>'4' 
        ); 
       echo $msg= formjson(array(),array(),$arrayjson1); 
       return $msg; 
      } 
     } 
     return 'ok'; 
    } 
    function login($loginUsername,$loginpassword){ 
     //query for checking user username exist or not 
     $sql="select count(*) from users where username=?"; 
     $count=Db::getValue($sql,$loginUsername); 
     if($count<=0){ 
      $msg=geterrormsg(1); 
      $arrayjson1=array(
         'success' => false, 
         'message'=>$msg, 
         'error_code'=>'1' 
        ); 
      echo $msg= formjson(array(),array(),$arrayjson1); 
      return $msg; 
     } 
     $sql="select AES_DECRYPT(password,'text') as password,userid from users where username=?"; 
     $row=Db::getRow($sql,$loginUsername); 
     if(is_array($row)) extract($row); 
     $this->userid=$userid; 
     //for checking password 
     if($loginpassword != $password){ 
      $msg=geterrormsg(2); 
      $arrayjson1=array(
         'success' => false, 
         'message'=>$msg, 
         'error_code'=>'2' 
        ); 
      echo $msg= formjson(array(),array(),$arrayjson1); 
      return $msg; 
     } 

     //query for checking user exist in session table with status =1 

     //~ $ses_id = session_id(); 
     //~ $_SESSION['username']=$loginUsername; 
     //~ $_SESSION['userid']=$userid; 
     //~ $sql="DELETE FROM sessions WHERE userid=? or id_session=?"; 
     //~ Db::execute($sql,array($userid,$ses_id)); 
      //~ $sql="INSERT INTO sessions (id_session, userid,  START, 
     //~ END, STATUS,  last_update) VALUES (?, ?,current_timestamp, 'end', '1', current_timestamp );"; 
     //~ Db::execute($sql,array($ses_id,$userid));  

     $gibid=$this->getDefaultGibId();   
     //making user array 
     $row=$this->getDetail(); 
     unset($row['updatedon'],$row['createdon']); 

     $gib=new Gib(array('gibid'=>$gibid)); 
     //~ $gibs=$gib->getgibs($userid,'',5); 
     $systemgibid=$gib->systemgibid(); 
     $arrayjson1=array(
        'success' => true, 
        'message'=>'User logged in successfully', 
        'gibid'=>$gibid, 
        'systemgibid'=>$systemgibid 
       ); 
     echo $msg= formjson(array(),$row,$arrayjson1); 
     return $msg;  

    } 
    function getDefaultGibId(){ 
     $sql="SELECT referid FROM cards WHERE userid_from=? AND userid_to=? and card_type='A' " ; 
     $gibid=Db::getValue($sql,array($this->userid,$this->userid)); 
     return $gibid; 
    } 

    //making user array 
    function getDetail(){ 
     $sql="select * from users where userid=?"; 
     $row=Db::getRow($sql,$this->userid); 
     unset($row['password']); 
     return $row; 
    } 
    // for creating new user 
    // will have one user entry , one profile card entry in card table , one system gib 
    function adduser(){ 
     $sql = "INSERT INTO users (username, firstname, lastname, PASSWORD,email,createdon ) 
      VALUES (?, ?, ?, AES_ENCRYPT(?,'text'),?,current_timestamp);"; 
     Db::execute($sql,array($this->username,  $this->firstname, $this->lastname,$this->password,$this->email)); 
     $this->userid=Db::getLastInsertId(); 
     //make profile card in cards table... 
     $sql="INSERT INTO cards(userid_from, userid_to,card_type, referid,status,createdon)VALUES(?, ?, ?, ?, ?,current_timestamp)"; 
     Db::execute($sql,array($this->userid,$this->userid,'V',$this->userid,'A')); 

     $id_card=Db::getLastInsertId(); 
     $gib=new Gib(array()); 
     $systemgibid=$gib->systemgibid(); 
     //make system gib card in cards table... 
     $sql="INSERT INTO cards(userid_from, userid_to, referid, 
      card_type ,status,createdon)VALUES(?, ?, ?,?,?,current_timestamp)" ; 
     Db::execute($sql,array($this->userid,$this->userid,$systemgibid,'A','A')); 
     $this->firstname=$this->firstname."'s Gib"; 
     //create gibs define in connection.php type D for default gib 
     $gib->creategib($this->firstname,'D',$this->userid,'',''); 
     $arrayjson=array(); 
     $row=$this->getDetail(); 

     $arrayjson1=array(
      'success' => true, 
      'message'=>'Registered in successfully', 
      'username'=>$this->username 
     ); 
     echo $msg= formjson($arrayjson,$row,$arrayjson1); 
     return $msg; 
    } 
    function updateuser(){ 
     $sql="UPDATE users SET firstname = ?, lastname = ?, email=? WHERE userid = ? "; 
     Db::execute($sql,array($this->firstname,$this->lastname,$this->email,$this->userid)); 
     $user=$this->getDetail(); 
     $arrayjson1=array(
      'success' => true, 
      'message'=>'form submission complete' 
     ); 
     echo $msg= formjson(array(),$user,$arrayjson1); 
     return $msg; 
    } 
    function changepassword($old_pswd,$new_pswd,$confirm_pswd){ 

     $sql="select count(*) from users where password=AES_ENCRYPT(?,'text') and userid=? "; 
     $count=Db::getValue($sql,array($old_pswd,$this->userid)); 
     if($count<=0){ 
      $msg=geterrormsg(28); 
      //old passwod not matched 
      $arrayjson1=array(
       'success' => false, 
       'message'=>$msg, 
       'error_code'=>'28' 
      ); 
      echo $msg= formjson(array(),array(),$arrayjson1); 
      return $msg; 
     } 
     //checking confirm and new password 
     if($new_pswd!=$confirm_pswd){ 
      $msg=geterrormsg(29); 
      $arrayjson1=array(
       'success' => false, 
       'message'=>$msg, 
       'error_code'=>'29' 
      ); 
      echo $msg= formjson(array(),array(),$arrayjson1); 
      return $msg; 
     } 
     $sql="UPDATE users SET PASSWORD = AES_ENCRYPT(?,'text') 
      WHERE userid = ? ; "; 
     Db::Execute($sql,array($new_pswd,$this->userid)); 
     $arrayjson1=array(
      'success' => true, 
      'message'=>'password changed successfully .', 
      'userid'=>$this->userid 
     ); 
     echo $msg= formjson(array(),array(),$arrayjson1); 
     return $msg; 
    } 
    function changeimage(){ 

     $sql="UPDATE users SET thumbnail=? ,url=?, avatar=?,crop_position=?, crop_url=? WHERE userid = ? "; 
     Db::Execute($sql,array($this->thumbnail,$this->url,$this->avatar,$this->crop_position,$this->crop_url,$this->userid)); 
     $user=$this->getDetail(); 
     $arrayjson1=array(
      'success' => true, 
      'message'=>'form submission complete' 
     ); 
     echo $msg= formjson(array(),$user,$arrayjson1);  
    } 
    function logout($id_session){ 
     //~ $sql="delete from sessions where userid=? and id_session=?"; 
     //~ Db::Execute($sql,array($this->userid,$id_session)); 

     //~ $sql="delete from occupants where userid=?"; 
     //~ Db::Execute($sql,$this->userid); 

     //~ unset($_SESSION['username']); 
     //~ session_destroy(); // start up your PHP session! 


     //~ echo $msg= "{'success': 'true','message':'logout successfully','userid':'$userid'}"; 
     return $msg; 
    } 
    function getuser($getuser){ 
     $userid=$getuser['userid']; 
     $name=$getuser['name']; 
     $pagelength=$getuser['pagelength']; 
     $pagenumber=$getuser['pagenumber']; 
     $fields=$getuser['fields']; 


     $condition = ''; 
     $query=array(); 

     if($userid !='') { 
      $condition .= " and userid=? "; 
      array_push($query,$userid); 
     } 
     if($name!=''){ 
      $condition .= " and concat_ws(' ',firstname,lastname) like ?"; 
      array_push($query,"%".$name."%"); 
     } 

     if($pagelength!=''){ 
      $limitpagelength="limit $pagelength"; 
     } 

     if($pagenumber!=''){ 
      $pagenumber=$pagelength*($pagenumber-1); 
      $pagenumber="offset $pagenumber"; 
     } 
     if($fields=='*'){ 
      $fields=",users.*"; 
     }elseif($fields!=''){ 
      $fields=",".$fields; 
     } 


     $sql="select userid,concat_ws(' ',firstname,lastname) as name $fields 
      from users where 1=1 $condition order by updatedon $limitpagelength $pagenumber"; 
     $row=Db::getResult($sql,$query); 

     $user=array(); 
     for($i=0;$i<count($row);$i++){ 
      unset($row[$i]['password']); 
      extract($row[$i]); 
      $this->userid=$userid; 
      $row[$i]['gibid']=$this->getDefaultGibId(); 
      array_push($user,$row[$i]); 
     } 


     $arrayjson1=array(
      'success' => true, 
      'message'=>'User data successfully', 
      'users'=>$user 
     ); 
     echo $msg= formjson(array(),array(),$arrayjson1); 
     return $msg; 
    } 
    //making user array 
    function getuserarray($username){ 
     $sql="select * from users where username=?"; 
     $row=Db::getRow($sql,$username); 
     unset($row['password']); 
     return $row; 
    } 


} 


?> 

請建議我我如何提高我的代碼通過實施先進的和所有的oops概念。 如果您發現這個問題含糊不清,請提出改進​​建議。 謝謝

+1

這個問題很模糊,而且幾乎沒有任何事情可以改進它(問題)。 – deceze 2011-01-06 07:02:30

+0

@deceze好的:) – XMen 2011-01-06 07:06:43

回答

2

foreach($_REQUEST as $key=>$value){ 
    $$key=$value; 
} 

可縮短至

extract($_REQUEST); 

但是,這樣做有兩個原因是不安全的:

  1. Using $_REQUEST is insecure unless you know the order in which data was merged into it
  2. Extracting variables might potentially overwrite existing important variables.

由於您已經在做OOP,我建議將Request對象引入您的應用程序並通過它的API訪問任何請求參數。不是將Request數據提取到數組子集中,而是將整個Request對象傳遞給任何需要它的函數或方法,例如而不是

$connections = $connection->getlink($getlink); 

$connections = $connection->getlink($request); 

除此之外,@mario與replacing that switch/case block好點。基本上,您顯示的代碼是FrontController,它根據收到的輸入確定下一步要做什麼。因此,您可以將所有這些命令字符串變爲classes of their own,例如

class LoginCommand 
class SaveUserCommand 
… 

然後只是實例化命令和run an interface method,例如,所有這些命令必須在實例上實現的方法。然後,你可以用

$request   = new Request($_GET, $_POST); 
$commandClass = $request->getCommand() . 'Command'; 
$commandInstance = new $commandClass($request); 
$commandInstance->execute(); 

更換您的switch/case既然你有多個命令在同一對象的工作,例如「getLink」和「createLink」都適用於Connection,您可能還想考慮將這些相關命令分組到PageController

無論您介紹第二個參數「控制器」做這樣的事情

$controllerClass = $request->getController(); 
$controller  = new $controllerClass($request); 

call_user_func(array($controller, $request->getCommand())); 

或使用路由器控制器

$router   = new Router('routes.ini'); 
$controllerClass = $router->mapCommandToControllerClass($request); 
$controller  = new $controllerClass($request); 

call_user_func(array($controller, $request->getCommand())); 

是你映射到適當的方法的命令。

如果你這樣做,你已經非常接近MVC(並且忽略關於它是MVP還是HMVC,因爲它在網上)。所有這些的最重要因素是無論如何都將業務邏輯從表示層分離出來。

我不會在你的類除外我不相信ActiveRecord和評論認爲你應該separate the codequeries the database從不會在這些類膠囊包裹的數據業務運營的代碼。

最後,我發現你的代碼缺乏空格,而且很難閱讀。考慮以下Code Convention like PEAR。並使用PHP_CodeSniffer以確保您遵循該約定。

聲明:以上均不視爲產品代碼。這些僅僅是一些示例,可以讓您瞭解如何改進應用程序體系結構。

0

兩件事。可以使用ArrayObject :: ARRAY_AS_PROPS從ArrayObject派生User類(也可能是其他類)。這樣你就可以使用原來的數據,可以節省手動屬性填充。

class User extends ArrayObject { 

    function User($users) { // __construct 
     parent::__construct($users, 2); 

這樣您就可以訪問$ this [「username」]和$ this-> username用戶名。可能會在其他地方受益。

對於第一個腳本,嘗試用類和方法替換冗長的開關。您可以使用call_user_func(array("modules", $command))來調用它們。

豎起大拇指使用準備好的語句,順便說一句!

+0

擴展ArrayObject的建議聽起來像YAGNI,它也會使User類暴露整個ArrayObject API。 – Gordon 2011-01-06 09:33:55