1、使用引用是不是使我們的代碼更加的簡(jiǎn)潔劫谅,除此之外相對(duì)于第一種寫法氢妈,我們節(jié)省了內(nèi)存空間粹污,尤其是再操作一個(gè)大數(shù)組時(shí)效果是及其明顯的。
2首量、使用匿名函數(shù)
Class One
{
private $instance;
// 類 One 內(nèi)部依賴了類 Two
// 不符合設(shè)計(jì)模式的最少知道原則
public function __construct()
{
$this->instace = new Two();
}
public function doSomething()
{
if (...) {
// 如果某種情況調(diào)用類 Two 的實(shí)例方法
$this->instance->do(...);
}
....
}
}
...
$instance = new One();
$instance->doSomething();
上面代碼寫法的問題:
不符合設(shè)計(jì)模式的最少知道原則壮吩,類 One 內(nèi)部直接依賴了類 Two进苍;
類 Two 的實(shí)例不是所有的上下文都會(huì)用到,所以浪費(fèi)了資源鸭叙。用單例觉啊,也無法解決實(shí)例化了不用的尷尬。
使用匿名函數(shù)進(jìn)行改寫:
Class One
{
private $closure;
public functionn __construct(Closure $closure)
{
$this->closure = $closure;
}
public function doSomething()
{
if (...) {
// 用的時(shí)候再實(shí)例化沈贝,實(shí)現(xiàn)懶加載
$instance = $this->closure();
$instance->do(...);
}
}
}
...
$instance = new One(function() {
return new Two();
});
$instance->doSomething();
...
3杠人、減少對(duì) if...else..的使用∷蜗拢可先使用 if 來處理簡(jiǎn)單異常嗡善,提前 return,再執(zhí)行正常邏輯
Function doSomething() {
if (...) {
if (...) {
...
} else {
...
}
} else {
if (...) {
...
} else {
...
}
}
}
細(xì)心的你會(huì)發(fā)現(xiàn)学歧,上面絕大多數(shù) else 代碼里都是在處理異常情況罩引,更可能這個(gè)異常代碼特別簡(jiǎn)單,那么就可以先去處理異常撩满,提前 return蜒程,再執(zhí)行正常的邏輯绅你。
function doSomething() {
if (...) {
// 異常情況
return ...;
}
if (...) {
// 異常情況
return ...;
}
// 正常邏輯
....
}
Class One
{
public function doSomething() {
if (...) {
throw new Exception(...);
}
if (...) {
throw new Exception(...);
}
// 正常邏輯
...
}
}
4伺帘、關(guān)聯(lián)數(shù)組做 map
做決策,通常會(huì)判斷不同的上下文忌锯,再選擇不同策略伪嫁,通常會(huì)像下面一樣使用 if 或者 switch 判斷:
Class One
{
public function doSomething()
{
if (...) {
$instance = new A();
} elseif (...) {
$instance = new A();
} else{
$instance = new C();
}
$instance->doSomething(...);
...
}
}
Class One {
private $map = [
'a' => 'namespace\A',
'b' => 'namespace\B',
'c' => 'namespace\C'
];
public functin doSomething()
{
....
$instance = new $this->map[$strategy];
$instance->doSomething(...);
}
}
```
5、使用接口
為什么要使用接口偶垮?便于后期的擴(kuò)展和代碼的可讀性张咳,例如:設(shè)計(jì)一個(gè)優(yōu)惠系統(tǒng),不同的商品知識(shí)再不同的優(yōu)惠策略下具備不同的優(yōu)惠行為似舵,我們定義一個(gè)優(yōu)惠行為的接口脚猾,最后對(duì)這個(gè)接口編程即可,偽代碼如下:
```
Interface Promotion
{
public function promote(...);
}
Class OnePromotion implement Promotion
{
public function doSomething(...) {
...
}
}
Class TwoPromotion implement Promotion
{
public function doSomething(...)
{
...
}
}
```
6砚哗、控制器不要有直接的 DB 操作
程序絕大多數(shù)的操作基本都是增刪改查龙助,可能是查詢的 where 條件和字段不同。所以可以抽象的把對(duì)數(shù)據(jù)庫(kù)增刪改查的方法寫到 model 中蛛芥,通過參數(shù)暴露我們的 where提鸟,fields 條件。
> 文章摘錄來源:http://tigerb.cn/2017/06/01/artisan/