php 是弱类型语言,通常情况下,是不去定义变量类型的。但是如果是java或者.net的开发人员转做php会不适应。或者是自己想自己写一个类似于 hibernate的orm框架的时候,没有实体类的概念,就不那么好控制了,那么简单讲下,怎么在php中实现实体类的概念。
首先建一个基本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中使用实体类的详细内容。