当前位置:网站首页>Use references
Use references
2022-07-07 11:32:00 【Full stack programmer webmaster】
### Using a reference
** Scene one : Traverse an array to get a new data structure **
Maybe you'll write :
“` // Declare a new array , Assemble the data you want $tmp = []; foreach ($arr as $k => $v) { // Take out the data you want $tmp[$k][‘youwant’] = $v[‘youwant’]; … // A series of judgments get the data you want if (…) { $tmp[$k][‘youwantbyjudge’] = ‘TIGERB’; } … } // Finally, you need the array you want $tmp
——————————————————-
// Maybe you don't think the above writing is very good , Let's write it another way foreach ($arr as $k => $v) { // A series of judgments get the data you want if (…) { // Replication value is what you want $arr[$k][‘youwantbyjudge’] = ‘TIGERB’ } … // Get rid of structures you don't want unset($arr[$k][‘youwantdel’]); } // Finally, we get our target array $arr “`
Next we use reference values :
“` foreach ($arr as &$v) { // A series of judgments get the data you want if (…) { // Replication value is what you want $v[‘youwantbyjudge’] = ‘TIGERB’ } … // Get rid of structures you don't want unset($v[‘youwantdel’]); } unset($v); // Finally, we get our target array $arr “`
Does using references make our code more concise , In addition, compared with the first writing , We save memory space , Especially when operating a large array, the effect is extremely obvious .
** Scene two : Pass a value to a function to get a new value **
Basically consistent with array traversal , We only need to declare this parameter of this function as a reference , as follows :
“` function decorate(&$arr = []) { # code… }
$arr = [ …. ]; // Call function decorate($arr); // The new value is obtained as above $arr, The advantage is to save memory space
“`
### Use try…catch…
Suppose there is the following logic : “` class UserModel { public function login($username = ”, $password = ”) { code… if (…) { // The user doesn't exist return -1; } code… if (…) { // Wrong password return -2; } code… } }
class UserController { public function login($username = ”, $password = ”) { $model = new UserModel(); $res = $model->login($username, $password); if ($res === -1) { return [ ‘code’ => ‘404’, ‘message’ => ‘ The user doesn't exist ’ ]; } if ($res === -2) { return [ ‘code’ => ‘400’, ‘message’ => ‘ Wrong password ’ ]; } code… } } “`
We use it try…catch… After rewriting : “` class UserModel { public function login($username = ”, $password = ”) { code… if (…) { // The user doesn't exist throw new Exception(‘ The user doesn't exist ’, ‘404’); } code… if (…) { // Wrong password throw new Exception(‘ Wrong password ’, ‘400’); } code… } }
class UserController { public function login($username = ”, $password = ”) { try { $model = new UserModel(); $res = $model->login($username, $password); // If necessary , We can unify here commit Database transactions // $db->commit(); } catch (Exception $e) { // If necessary , We can unify here rollback Database transactions // $db->rollback(); return [ ‘code’ => $e->getCode(), ‘message’ => $e->getMessage() ] } } } “`
By using try…catch… Make our code logic clearer ,try… We only need to pay attention to the normal business situation , Exception handling is unified in catch in . therefore , We can throw an exception directly when writing upstream code .
### Using anonymous functions
** Build code blocks inside functions or methods **
Suppose we have a logic , In a function or method, we need to format data , But this code fragment for formatting data appears many times , If we write directly, we may think of the following :
“` function doSomething(…) { … // Format code snippets … … // Format code snippets [ Duplicate code ] … } “`
I believe most people should not write like this , May be like this :
“` function doSomething(…) { … format(…); … format(…); … }
// Then declare a function or method that takes the form of code function format() { // Format code snippets … } “`
There is no problem with the above writing , Minimize our code snippets , But if this format Functions or methods are just doSomething How to use it? ? I usually write like this , Why? ? Because I think in this context format and doSomething A subset of .
“` function doSomething() { … $package = function (…) use (…) { // Again use The following parameters can also be passed by reference // Format code snippets … }; … package(…); … package(…); … } “`
** Implementation class 【 Lazy loading 】 And implement design patterns 【 Least known principle 】 **
If there is the following code :
“` class One { private $instance;
// class One Internally depends on the class Two // It does not conform to the principle of least knowing of design patterns public function __construct() { $this->intance = new Two(); }
public function doSomething() { if (…) { // If a class is called under certain circumstances Two Instance method of $this->instance->do(…); } … } } …
$instance = new One(); $instance->doSomething(); … “`
What's wrong with the above writing ?
– It does not conform to the principle of least knowing of design patterns , class One The internal directly depends on the class Two – class Two Instances of are not used in all contexts , So it wastes resources , Some people say to make a single case , But it can't solve the embarrassment of not using instantiation
So we use anonymous functions to solve the above problem , Let's rewrite it like this :
“` class One { private $closure;
public function __construct(Closure $closure) { $this->closure = $closure; }
public function doSomething() { if (…) { // Instantiate when using // Implement lazy loading $instance = $this->closure(); $instance->do(…) } … } } …
$instance = new One(function () { // class One Externally dependent classes Two return new Two(); }); $instance->doSomething(); … “`
### Reduce to if…else… Use
If you come across this type of code , It must be a black hole .
“` function doSomething() { if (…) { if (…) { … } esle { … } } else { if (…) { … } esle { … } } }
“`
** advance return abnormal **
Careful you may find the above situation , Maybe most of them else The code is dealing with exceptions , More likely, the exception code is particularly simple , Usually I do this :
“` // If it is in a function, I will deal with the exception first , And then ahead of time return Code , Finally, execute the normal logic function doSomething() { if (…) { // Abnormal situation return …; } if (…) { // Abnormal situation return …; } // Normal logic … }
// Again , If it is in a class, I will deal with the exception first , Then throw an exception first class One { public function doSomething() { if (…) { // Abnormal situation throw new Exception(…); } if (…) { // Abnormal situation throw new Exception(…); } // Normal logic … } }
“`
** Associative array do map **
If we make decisions on the client , Usually we will judge that different contexts are choosing different strategies , It is usually used as follows if perhaps switch Judge :
“` class One { public function doSomething() { if (…) { $instance = new A(); } elseif (…) { $instance = new A(); } else { $instance = new C(); } $instance->doSomething(…); … } } “`
There are usually a lot of if Statements or switch sentence , Usually I use one map To map different strategies , Like this :
“` class One { private $map = [ ‘a’ => ‘namespace\A’, // Bring the namespace , Because variables are dynamic ‘b’ => ‘namespace\B’, ‘c’ => ‘namespace\C’ ]; public function doSomething() { … $instance = new $this->map[$strategy];// $strategy yes ’a’ or ’b’ or ’c’ $instance->doSomething(…); … } } “`
### Use interface
Why use interfaces ? It is very convenient for later expansion and code readability , For example, designing a preferential system , Different goods only have different preferential behaviors under different preferential strategies , We define an interface for preferential behavior , Finally, program this interface , The pseudocode is as follows
“` Interface Promotion { public function promote(…); }
class OnePromotion implement Promotion { public function doSomething(…) { … } }
class TwoPromotion implement Promotion { public function doSomething(…) { … } } “`
### The controller rejects direct DB operation
Finally, I want to say that I will never refuse to be in your Controller Direct operation in DB, Why? ? Most operations of our program are basically adding, deleting, modifying and checking , It may be queried where Conditions and fields are different , So sometimes we can write the methods of adding, deleting, modifying and querying the database abstractly model in , Expose our where,fields Conditions . Usually, this can greatly improve efficiency and code reuse . Like this :
“` class DemoModel implement Model { public function getMultiDate($where = [], $fields = [‘id’], $orderby = ‘id asc’) { $this->where($where) ->field($fields) ->orderby($orderby) ->get(); } } “`
### Last
If there is something wrong with it , Welcome to correct ,THX~
> [Easy PHP: A very fast lightweight PHP Full stack framework ](http://php.tigerb.cn/)
Publisher : Full stack programmer stack length , Reprint Please indicate the source :https://javaforall.cn/113821.html Link to the original text :https://javaforall.cn
边栏推荐
- How to remove addition and subtraction from inputnumber input box
- 关于测试人生的一站式发展建议
- 测试优惠券要怎么写测试用例?
- About the application of writing shell script JSON in JMeter
- What if copying is prohibited?
- 聊聊SOC启动(六)uboot启动流程二
- How to add aplayer music player in blog
- Talk about SOC startup (VII) uboot startup process III
- Vuthink proper installation process
- Leetcode - interview question 17.24 maximum submatrix
猜你喜欢
Reasons for the failure of web side automation test
Talk about SOC startup (IX) adding a new board to uboot
Le Cluster kubernets en cours d'exécution veut ajuster l'adresse du segment réseau du pod
Avoid mutating a prop directly since the value will be overwritten whenever the parent component
关于测试人生的一站式发展建议
技术分享 | 抓包分析 TCP 协议
关于在云服务器上(这里用腾讯云)安装mysql8.0并使本地可以远程连接的方法
RationalDMIS2022 高级编程宏程序
浙江大学周亚金:“又破又立”的顶尖安全学者,好奇心驱动的行动派
聊聊SOC启动(十) 内核启动先导知识
随机推荐
竟然有一半的人不知道 for 与 foreach 的区别???
90后,辞职创业,说要卷死云数据库
EasyUI learn to organize notes
R Language Using Image of magick package Mosaic Function and Image La fonction flatten empile plusieurs images ensemble pour former des couches empilées sur chaque autre
verilog设计抢答器【附源码】
Design intelligent weighing system based on Huawei cloud IOT (STM32)
【时间格式工具函数的封装】
Process control (creation, termination, waiting, program replacement)
Android 面试知识点
Talk about SOC startup (11) kernel initialization
Half of the people don't know the difference between for and foreach???
聊聊SOC启动(七) uboot启动流程三
聊聊SOC启动(六)uboot启动流程二
Easyui学习整理笔记
Graduation season | keep company with youth and look forward to the future together!
R language uses the quantile function to calculate the quantile of the score value (20%, 40%, 60%, 80%), uses the logical operator to encode the corresponding quantile interval (quantile) into the cla
Blog moved to Zhihu
OneDNS助力高校行业网络安全
There are so many factors that imprison you
Activity lifecycle