简单谈谈PHP面向对象之标识对象
标识对象模式
这个模式主要功能就是创建sql语句中的wehre条件字符串的,下面直接看代码和注释:
namespacewoo\mapper;
//字段对象
classField{
protected$name=null;//字段名称
protected$operator=null;//操作符
protected$comps=array();//存放条件的数组
protected$incomplete=false;//检查条件数组是否有值
function__construct($name){
$this->name=$name;
}
//添加where条件
functionaddTest($operator,$value){
$this->comps[]=array('name'=>$this->name,'operator'=>$operator,'value'=>$value);
}
//获取存放条件的数组
functiongetComps(){
return$this->comps;
}
functionisIncomplete(){
returnempty($this->comps);
}
}
//标识对象
classIdentityObject{
protected$currentfield=null;//当前操作的字段对象
protected$fields=array();//字段集合
private$and=null;
private$enforce=array();//限定的合法字段
function__construct($field=null,array$enforce=null){
if(!is_null($enforce)){
$this->enforce=$enforce;
}
if(!is_null($field)){
$this->field($field);
}
}
//获取限定的合法字段
functiongetObjectFields(){
return$this->enforce;
}
//主要功能为设置当前需要操作的对象
functionfield($fieldname){
if(!$this->isVoid()&&$this->currentfield->isIncomplete()){
thrownew\Exception("Incompletefield");
}
$this->enforceField($fieldname);
if(isset($this->fields[$fieldname]){
$this->currentfield=$this->fields[$fieldname];
}else{
$this->currentfield=newField($fieldname);
$this->fields[$fieldname]=$this->currentfield;
}
return$this;//采用连贯语法
}
//字段集合是否为空
functionisVoid(){
returnempty($this->fields);
}
//检查字段是否合法
functionenforceField($fieldname){
if(!in_array($fieldname,$this->enforce)&&!empty($this->enforce)){
$forcelist=implode(',',$this->enforce);
thrownew\Exception("{$fieldname}notalegalfield{$forcelist}");
}
}
//向字段对象添加where条件
functioneq($value){
return$this->operator("=",$value);
}
functionlt($value){
return$this->operator("<",$value);
}
functiongt($value){
return$this->operator(">",$value);
}
//向字段对象添加where条件
privatefunctionoperator($symbol,$value){
if($this->isVoid){
thrownew\Exception("noobjectfielddefined");
}
$this->currentfield->addTest($symbol,$value);
return$this;//采用连贯语法
}
//获取此类中所有字段对象集合的where条件数组
functiongetComps(){
$ret=array();
foreach($this->fieldsas$key=>$field){
$ret=array_merge($ret,$field->getComps());
}
return$ret;
}
}
//客户端代码
$idobj=newIdentityObject();
$idobj->field("name")->eq("TheGoodShow")->field("start")->gt(time())->lt(time()+(24*60*60));
$test=$idobj->getComps();
var_dump($test);
//输出类似下面的内容
/*
array{
array('name'=>'name','operator'=>'=','value'=>'TheGoodShow'),
array('name'=>'start','operator'=>'>','value'=>'123456'),//123456表示time()函数输出的时间戳
array('name'=>'start','operator'=>'<','value'=>'123456')
}
*/
以上这篇简单谈谈PHP面向对象之标识对象就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。