当前位置:网站首页>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
边栏推荐
- Android interview knowledge points
- Easyui学习整理笔记
- 网络协议 概念
- 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
- 通过环境变量将 Pod 信息呈现给容器
- Neural approvals to conversational AI (1)
- How to remove addition and subtraction from inputnumber input box
- LeetCode - 面试题17.24 最大子矩阵
- Audit migration
- 本地navicat连接liunx下的oracle报权限不足
猜你喜欢
Automated testing framework
OneDNS助力高校行业网络安全
Socket socket programming
The post-90s resigned and started a business, saying they would kill cloud database
The database synchronization tool dbsync adds support for mongodb and es
数据库同步工具 DBSync 新增对MongoDB、ES的支持
在我有限的软件测试经历里,一段专职的自动化测试经验总结
一度辍学的数学差生,获得今年菲尔兹奖
Distributed database master-slave configuration (MySQL)
技术分享 | 抓包分析 TCP 协议
随机推荐
网络协议 概念
R language Visual facet chart, hypothesis test, multivariable grouping t-test, visual multivariable grouping faceting boxplot, and add significance levels and jitter points
The running kubernetes cluster wants to adjust the network segment address of pod
Audit migration
After the uniapp jumps to the page in onlaunch, click the event failure solution
通过 Play Integrity API 的 nonce 字段提高应用安全性
Technology sharing | packet capturing analysis TCP protocol
The post-90s resigned and started a business, saying they would kill cloud database
Debezium同步之Debezium架构详解
使用引用
Test the foundation of development, and teach you to prepare for a fully functional web platform environment
本地navicat连接liunx下的oracle报权限不足
Vuthink proper installation process
Android interview knowledge points
Antd select selector drop-down box follows the scroll bar to scroll through the solution
Input type= "password" how to solve the problem of password automatically brought in
Half of the people don't know the difference between for and foreach???
Design intelligent weighing system based on Huawei cloud IOT (STM32)
RationalDMIS2022 高级编程宏程序
Common SQL statement collation: MySQL