php 是弱類型語言,通常情況下,是不去定義變數類型的。但是如果是JAVA或者.NET的開發人員轉做PHP會不適應。或者是自己想自己寫一個類似於 hibernate的orm架構的時候,沒有實體類的概念,就不那麼好控制了,那麼簡單講下,怎麼在php中實現實體類的概念。
首先建一個基本Model類
<?phpclass BaseModel{private $_tableName;public function construct($tableName=""){$this->_tableName=$tableName;}public function getTableName(){return $this->_tableName;}public function getFieldsArray(){try {$obj=json_decode(json_encode($this),true); //此處可能會影響效率,但是為了去除類中的private屬性,目前是這麼做的$fieldsArray=array();foreach ($obj as $k=>$v){$fieldsArray[]=$k;}return $fieldsArray;} catch (Exception $e) {throw new Exception($e,3, $previous);}}public function find($condition=null){try {$sql="select ".implode(",",$this->getFieldsArray())." from ".$this->_tableName." ";if($condition){$sql.=" where ".$condition;}else {$obj=json_decode(json_encode($this),true);$fieldsArray=array();foreach ($obj as $k=>$v){if($v!=null && $v!=""){$fieldsArray[]=$k."='".$v."'";}}if(count($fieldsArray)>0){$sql.=" where ".implode(" and ", $fieldsArray);}}return $sql;} catch (Exception $e) {throw new Exception($e,3, $previous);}}}?>
下面來建一個對應資料庫中表的將在項目中使用的類
<?phpclass MemberModel extends BaseModel{public $m_ID;public $m_Account;public $m_Pwd;public $m_TEL;public $m_UserID;public $m_ChannelID;public $m_Status;public $m_CreateTime;public $m_UpdateTime;}?>
下面就是實體類如何去使用的了
首次看controller
public function actionSelectMember(){try {$member=new MemberModel("T_Member");$member->m_Account=GetValue::getParam("Account");$member->m_Pwd=GetValue::getParam("Pwd");$result=MemberService::selectMember($member);if($result){Yii::app()->session["MemberID"]=$result["m_ID"];echo IMReturnStr::success();}else {echo IMReturnStr::GetInfo(false,"使用者名稱或者密碼錯誤");}} catch (Exception $e) {echo IMReturnStr::failure();}}
service
public static function selectMember(MemberModel $member){
try {
return MemberDao::selectMember($member);
} catch (Exception $e) {
throw new Exception($e,4);
}
}
dao
public static function selectMember(MemberModel $member){ //這裡就是為什麼要寫類型了,寫了類型可以拿到定義的類中的方法,否則雖然也可以直接寫,但是沒有自動提示,如果用的方法比較多,就很蛋疼了。try {$sql=$member->find();return YIISqlOper::queryRow($sql);} catch (Exception $e) {throw new Exception($e,4);}}