当前位置:网站首页>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
边栏推荐
- Eth trunk link switching delay is too high
- 使用MeterSphere让你的测试工作持续高效
- PostgreSQL中的表复制
- STM32 entry development uses IIC hardware timing to read and write AT24C08 (EEPROM)
- 分布式数据库主从配置(MySQL)
- 基于华为云IOT设计智能称重系统(STM32)
- 科普达人丨一文弄懂什么是云计算?
- Case study of Jinshan API translation function based on retrofit framework
- Talk about SOC startup (11) kernel initialization
- 竟然有一半的人不知道 for 与 foreach 的区别???
猜你喜欢

The running kubernetes cluster wants to adjust the network segment address of pod

Force buckle 1002 Find common characters

Half of the people don't know the difference between for and foreach???

Use metersphere to keep your testing work efficient

How to add aplayer music player in blog

测试开发基础,教你做一个完整功能的Web平台之环境准备

90后,辞职创业,说要卷死云数据库

如何在博客中添加Aplayer音乐播放器

基于华为云IOT设计智能称重系统(STM32)

What if copying is prohibited?
随机推荐
In depth learning autumn recruitment interview questions collection (1)
Network protocol concept
分布式数据库主从配置(MySQL)
R语言可视化分面图、假设检验、多变量分组t检验、可视化多变量分组分面箱图(faceting boxplot)并添加显著性水平、添加抖动数据点(jitter points)
解决VSCode只能开两个标签页的问题
R language Visual facet chart, hypothesis test, multivariable grouping t-test, visual multivariable grouping faceting boxplot, and add significance levels and jitter points
聊聊SOC启动(七) uboot启动流程三
The opacity value becomes 1%
electron添加SQLite数据库
使用引用
Antd select selector drop-down box follows the scroll bar to scroll through the solution
软件设计之——“高内聚低耦合”
'module 'object is not callable error
博客搬家到知乎
Electron adding SQLite database
竟然有一半的人不知道 for 与 foreach 的区别???
Socket socket programming
JS array delete the specified element
Graduation season | keep company with youth and look forward to the future together!
网络协议 概念