当前位置:网站首页>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
边栏推荐
- ‘module‘ object is not callable错误
- electron添加SQLite数据库
- Neural approvals to conversational AI (1)
- Excel公式知多少?
- Case study of Jinshan API translation function based on retrofit framework
- The concept, implementation and analysis of binary search tree (BST)
- Reasons for the failure of web side automation test
- 正在运行的Kubernetes集群想要调整Pod的网段地址
- 关于测试人生的一站式发展建议
- Leetcode - interview question 17.24 maximum submatrix
猜你喜欢
Onedns helps college industry network security
OneDNS助力高校行业网络安全
通过 Play Integrity API 的 nonce 字段提高应用安全性
Design intelligent weighing system based on Huawei cloud IOT (STM32)
正在運行的Kubernetes集群想要調整Pod的網段地址
The concept, implementation and analysis of binary search tree (BST)
如何在博客中添加Aplayer音乐播放器
解决VSCode只能开两个标签页的问题
在我有限的软件测试经历里,一段专职的自动化测试经验总结
Debezium同步之Debezium架构详解
随机推荐
R语言使用magick包的image_mosaic函数和image_flatten函数把多张图片堆叠在一起形成堆叠组合图像(Stack layers on top of each other)
Half of the people don't know the difference between for and foreach???
博客搬家到知乎
聊聊SOC启动(六)uboot启动流程二
STM32 entry development uses IIC hardware timing to read and write AT24C08 (EEPROM)
毕业季|与青春作伴,一起向未来!
Drive HC based on de2115 development board_ SR04 ultrasonic ranging module [source code attached]
请查收.NET MAUI 的最新学习资源
Antd select selector drop-down box follows the scroll bar to scroll through the solution
深度学习秋招面试题集锦(一)
STM32 entry development NEC infrared protocol decoding (ultra low cost wireless transmission scheme)
R语言可视化分面图、假设检验、多变量分组t检验、可视化多变量分组分面箱图(faceting boxplot)并添加显著性水平、添加抖动数据点(jitter points)
electron添加SQLite数据库
R語言使用magick包的image_mosaic函數和image_flatten函數把多張圖片堆疊在一起形成堆疊組合圖像(Stack layers on top of each other)
数据库同步工具 DBSync 新增对MongoDB、ES的支持
基于DE2 115开发板驱动HC_SR04超声波测距模块【附源码】
Excel公式知多少?
Eth trunk link switching delay is too high
audit 移植
解决VSCode只能开两个标签页的问题