时间:2021-07-01 10:21:17 帮助过:16人阅读
首先建一个基本Model类
<?php class 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); } } } ?>
下面来建一个对应数据库中表的将在项目中使用的类
<?php class 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); } }
以上就是怎么在php中使用实体类的详细内容,更多请关注Gxl网其它相关文章!