PHP和Java代码实例分析
PHP和Java代码实例分析
这篇文章主要介绍“PHP和Java代码实例分析”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“PHP和Java代码实例分析”文章能帮助大家解决问题。
命名
案例1
functiongetGoods($query,$shopId){$goodsId=Goods::add($query["uid"],$query["name"]);returnShop::add($goodsId,$shopId);}classGoods{publicstaticfunctionadd($uid,$name){$id=mt_rand(1,100000);return$id;}}classShop{publicstaticfunctionadd($goodsId,$shopId){$id=mt_rand(1,100000);return$id;}}
案例2
functiongetUserInfo($teamId,$youId=[]){}
如果仅仅有这个函数名和参数名,谁能猜到参数的意义呢?
案例3
classDb{/***@paramstring$table数据库表名*@paramarray$data新增数据**@returnint新增主键*/publicstaticfunctioninsert(string$table,array$data){$id=mt_rand(1,1000);return$id;}}classViewLogStore{private$table="view_log";functionsetHistory($data){Db::insert($this->table,$data);}}
案例4
假如业务代码里有这些类
classWechatUserModel{}classWechatGroupModel{}classWechatMessageModel{}
而我们查询数据库发现
这样我们根据业务代码就非常不方便找到对应的表,而且其他人接手我们项目的时候,也会摸不着头脑。或者说这可能是三个人三次迭代开发造成的,那么他们彼此都没有去参考前面人的命名规则。
来自灵魂的拷问
注释
说完命名,下面说下注释。注释里还有什么学问?Are you kidding me?
一个数组对象成员,你知道怎么写吗?
类的魔术方法调用的注释,你知道怎么写吗?
对象数组
/***@varAds[]*/public$adsList=[];
$blocks=[];/**@var$blocksBlock[]**/
@method 的使用
/***@linkhttp://manual.phpdoc.org/HTMLframesConverter/default/**@methodstaticintsearch(string$query,$limit=10,$offset=0)*/classSearchServiceProxy{publicstaticfunction__callStatic($method,$arguments){if(!method_exists("SearchService",$method)){thrownew\LogicException(__CLASS__."::".$method."notfound");}try{$data=call_user_func_array(["SearchService",$method],$arguments);}catch(\Exception$e){error_log($e->getMessage());returnfalse;}return$data;}}
@deprecated 使用
classSearchService{/***@paramstring$query*@paramint$limit*@paramint$offset**@returnarray*@deprecated*/publicstaticfunctionsearch(string$query,$limit=10,$offset=0){return[["id"=>1,"aaa"],["id"=>2,"bbb"],];}}
注释其他注意事项
注释解释张冠李戴,方法名更新,方法的功能业务注释没更新;复制别人的代码把 @author 信息也复制过来了,错误了还要把锅甩给别人。
注释更多参考 http://manual.phpdoc.org/HTML...
函数、方法
案例1
先说明一句,不好的代码不妨碍它成为一个优秀的软件。PHP MySQL 烂代码多的去了。
找到一个开源软件里面的代码,功能非常抢到,但是这个方法内容太多,一些不足点我标注出来了。
案例2
拿上面我举例子,还记得下面这种图吗?
优化方案1
classArrayUtils{publicstaticfunctionfetch($arr,$keys,$setNull=false){$ret=array();foreach($keysas$key){if($setNull){$ret[$key]=$arr[$key];}else{isset($arr[$key])&&$ret[$key]=$arr[$key];}}return$ret;}}classViewLogStore{private$table="view_log";functionrecord($data){$fields=array('uid','url','referer','created_time');$data=ArrayUtils::fetch($data,$fields);Db::insert($this->table,$data);}}
优化方案2
classDb{/***@paramstring$table数据库表名*@paramEntity$data新增对象**@returnint新增主键*/publicstaticfunctioninsert(string$table,Entity$data){$array=$data->toArray();var_export($array);//test$id=mt_rand(1,1000);return$id;}}classArrayUtils{/***针对成员都是私有属性的对象**@param$obj*@parambool$removeNull去掉空值*@parambool$camelCase**@returnarray*/publicstaticfunctionObj2Array($obj,$removeNull=true,$camelCase=true){$reflect=new\ReflectionClass($obj);$props=$reflect->getProperties(\ReflectionProperty::IS_PUBLIC|\ReflectionProperty::IS_PRIVATE|\ReflectionProperty::IS_PROTECTED);$array=[];foreach($propsas$prop){$prop->setAccessible(true);$key=$prop->getName();//如果不是驼峰命名方式,就把对象里面的createTime转成create_timeif(!$camelCase){$key=preg_replace_callback("/[A-Z]/",function($matches){return"_".strtolower($matches[0]);},$key);$key=ltrim($key,"_");}$value=$prop->getValue($obj);if($removeNull==true&&$value===null){continue;}if(is_object($value)){$value=self::Obj2Array($value);}$array[$key]=$value;}return$array;}}classEntity{publicfunctiontoArray(){returnArrayUtils::Obj2Array($this);}}classViewLogEntityextendsEntity{/***@varint*/private$uid;/***@varstring*/private$url;/***@varstring*/private$referer;/***@varstring*/private$createdTime;/***@paramint$uid*/publicfunctionsetUid(int$uid){$this->uid=$uid;}/***@paramstring$url*/publicfunctionsetUrl(string$url){$this->url=$url;}/***@paramstring$referer*/publicfunctionsetReferer(string$referer){$this->referer=$referer;}/***@paramstring$createdTime*/publicfunctionsetCreatedTime(string$createdTime){$this->createdTime=$createdTime;}}classViewLogStore{private$table="view_log";functionrecord(ViewLogEntity$viewLogEntity){Db::insert($this->table,$viewLogEntity);}}//测试$viewLogEntity=newViewLogEntity();$viewLogEntity->setUid(1);$viewLogEntity->setReferer("https://mengkang.net");$viewLogEntity->setUrl("https://segmentfault.com/l/1500000018225727");$viewLogEntity->setCreatedTime(date("Y-m-dH:i:s",time()));$viewLogStore=newViewLogStore();$viewLogStore->record($viewLogEntity);
案例3
这还是函数吗?(不仅仅是语义,属于错误)
/***@methodmixedfetchList(string$sql,array$argv);*/classModel{publicfunction__construct($table){}}functiongetUserList($startId,$lastId,$limit=100){if($lastId>0){$startId=$lastId;}$sql="select*from`user`whereid>?orderbyidasclimit?,?";$model=newModel('user');return$model->fetchList($sql,[intval($startId),intval($limit)]);}
$startId和$lastId两个参数重复
案例4
尽量减少参数引用
functionbad($input1,$input2,&$input3){//...logic$input3="xxx";returntrue;}
案例5
参数类型明确,返回值类型明确,不要出现 mixed。这个我直接拿官方的函数来举例,对权威也要有怀疑的眼光。纯属个人看法。
案例6
上面例子中你会发现这个addUser写得不想一个函数(方法)而像一个远程api接口。而且在右边的代码中需要每次使用的时候都要用is_array来判断。这是非常不友好的语义表达。PHP Java 这样的高级语言有异常,我们要善用异常。
关于“PHP和Java代码实例分析”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注恰卡编程网行业资讯频道,小编每天都会为大家更新不同的知识点。
推荐阅读
-
php字符串增加1如何实现
php字符串增加1如何实现这篇“php字符串增加1如何实现”文章的...
-
php如何判断字符串是否有中文
-
php如何实现字符串去掉头尾
-
php字符串的组成是什么
php字符串的组成是什么这篇文章主要讲解了“php字符串的组成是什...
-
php如何让Swoole/Pool进程池实现Redis持久连接
php如何让Swoole/Pool进程池实现Redis持久连接本篇...
-
php字符串长度不一致如何解决
-
php时区不正确如何解决
-
php+fread()乱码如何解决
php+fread()乱码如何解决本篇内容介绍了“php+frea...
-
php explode报错如何解决
-
linux Centos如何安装PHP7
linuxCentos如何安装PHP7今天小编给大家分享一下li...