Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Analysis of PHP and Java Code examples

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the relevant knowledge of "PHP and Java code case analysis". The editor shows you the operation process through the actual case. The operation method is simple, fast and practical. I hope this "PHP and Java code example analysis" article can help you solve the problem.

Naming

Case 1

Function getGoods ($query, $shopId) {$goodsId = Goods::add ($query ["uid"], $query ["name"]); return Shop::add ($goodsId, $shopId);} class Goods {public static function add ($uid, $name) {$id = mt_rand (1, 100000); return $id;} class Shop {public static function add ($goodsId, $shopId) {$id = mt_rand (1, 100000) Return $id;}}

Case 2

Function getUserInfo ($teamId, $youId = []) {}

If there is only this function name and parameter name, who can guess the meaning of the parameter?

Case 3

Class Db {/ * @ param string $table database table name * @ param array $data add data * * @ return int add primary key * / public static function insert (string $table, array $data) {$id = mt_rand (1, 1000); return $id;} class ViewLogStore {private $table = "view_log" Function setHistory ($data) {Db::insert ($this- > table, $data);}}

Case 4

If there are these classes in the business code

Class WechatUserModel {} class WechatGroupModel {} class WechatMessageModel {}

And we checked the database and found

In this way, it is very difficult for us to find the corresponding table according to the business code, and others will be confused when they take over our project. Or it could be the result of three iterations by three people, so they didn't refer to each other's naming rules.

Torture from the soul

Annotation

After saying the naming, let's talk about the notes below. Is there anything else in the notes? Are you kidding me?

An array object member, do you know how to write it?

Do you know how to write the comments for magic method calls of the class?

Object array / * * @ var Ads [] * / public $adsList = []

$blocks = []; / * @ var $blocks Block [] * /

The use of @ method

/ * * @ link http://manual.phpdoc.org/HTMLframesConverter/default/ * * @ method static int search (string $query, $limit = 10, $offset = 0) * / class SearchServiceProxy {public static function _ callStatic ($method, $arguments) {if (! method_exists ("SearchService", $method)) {throw new\ LogicException (_ _ CLASS__. ":" $method. "not found");} try {$data = call_user_func_array (["SearchService", $method], $arguments);} catch (\ Exception $e) {error_log ($e-> getMessage ()); return false;} return $data;}}

@ deprecated use

Class SearchService {/ * @ param string $query * @ param int $limit * @ param int $offset * * @ return array * @ deprecated * / public static function search (string $query, $limit = 10, $offset = 0) {return [["id" = > 1, "aaa"], ["id" = > 2, "bbb"] ] }}

Note other considerations

Comments explain the wrong object, the name of the method is updated, and the functional business comments of the method are not updated; copy other people's code to copy the @ author information, and throw the pot to others if you make a mistake.

For more notes, please see http://manual.phpdoc.org/HTML....

Function, method

Case 1

Just to be clear, bad code doesn't prevent it from becoming good software. There's a lot of bad code in PHP MySQL.

Find an open source software inside the code, the function is very grab, but this method content is too much, some deficiencies I marked out.

Case 2

Take me as an example above. Do you remember the picture below?

Optimization scheme 1

Class ArrayUtils {public static function fetch ($arr, $keys, $setNull = false) {$ret = array (); foreach ($keys as $key) {if ($setNull) {$ret [$key] = $arr [$key] } else {isset ($arr [$key]) & & $ret [$key] = $arr [$key];}} return $ret;}} class ViewLogStore {private $table = "view_log" Function record ($data) {$fields = array ('uid',' url', 'referer',' created_time'); $data = ArrayUtils::fetch ($data, $fields); Db::insert ($this- > table, $data);}}

Optimization scheme 2

Class Db {/ * * @ param string $table database table name * @ param Entity $data added object * * @ return int added primary key * / public static function insert (string $table, Entity $data) {$array = $data- > toArray (); var_export ($array); / / test $id = mt_rand (1, 1000); return $id }} class ArrayUtils {/ * for objects whose members are private attributes * * @ param $obj * @ param bool $removeNull remove the null value * @ param bool $camelCase * * @ return array * / public static function Obj2Array ($obj, $removeNull = true, $camelCase = true) {$reflect = new\ ReflectionClass ($obj) $props = $reflect- > getProperties (\ ReflectionProperty::IS_PUBLIC |\ ReflectionProperty::IS_PRIVATE |\ ReflectionProperty::IS_PROTECTED); $array = []; foreach ($props as $prop) {$prop- > setAccessible (true); $key = $prop- > getName () / / if it is not the hump naming method, convert the createTime in the object to create_time if (! $camelCase) {$key = preg_replace_callback ("/ [Amurz] /", 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;}} class Entity {public function toArray () {return ArrayUtils::Obj2Array ($this) }} class ViewLogEntity extends Entity {/ * * @ var int * / private $uid; / * * @ var string * / private $url; / * * @ var string * / private $referer; / * * @ var string * / private $createdTime / * * @ param int $uid * / public function setUid (int $uid) {$this- > uid = $uid;} / * * @ param string $url * / public function setUrl (string $url) {$this- > url = $url } / * * @ param string $referer * / public function setReferer (string $referer) {$this- > referer = $referer;} / * * @ param string $createdTime * / public function setCreatedTime (string $createdTime) {$this- > createdTime = $createdTime;}} class ViewLogStore {private $table = "view_log" Function record (ViewLogEntity $viewLogEntity) {Db::insert ($this- > table, $viewLogEntity);}} / / Test $viewLogEntity = new ViewLogEntity (); $viewLogEntity- > setUid (1); $viewLogEntity- > setReferer ("https://mengkang.net"); $viewLogEntity- > setUrl (" https://segmentfault.com/l/1500000018225727"); $viewLogEntity- > setCreatedTime (date ("Y-m-d H:i:s", time ()); $viewLogStore = new ViewLogStore (); $viewLogStore- > record ($viewLogEntity)

Case 3

Is this still a function? (it's not just semantic, it's an error)

/ * * @ method mixed fetchList (string $sql, array $argv); * / class Model {public function _ construct ($table) {} function getUserList ($startId, $lastId, $limit = 100) {if ($lastId > 0) {$startId = $lastId;} $sql = "select * from `user` where id >? Order by id asc limit?,? "; $model = new Model ('user'); return $model- > fetchList ($sql, [intval ($startId), intval ($limit)]);}

Duplicate parameters $startId and $lastId

Case 4

Minimize parameter references

Function bad ($input1, $input2, & $input3) {/ /... logic $input3 = "xxx"; return true;}

Case 5

The parameter type is clear, the return value type is clear, do not appear mixed. I will directly take the official function as an example, and I should also be skeptical of authority. It's purely personal.

Case 6

In the above example, you will find that this addUser is written not like a function (method) but like a remote api interface. And in the code on the right, you need to use is_array to judge every time you use it. This is a very unfriendly semantic expression. There are exceptions in a high-level language like PHP Java, so we should make good use of them.

So much for the introduction of "PHP and Java Code example Analysis". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report