PHP多行缩进,规范 - 只使用一层缩进

定义一个类用于管理银行账户

class BankAccount {

protected $accounts;

public function __construct($account)

{

$this->accounts = $account;

}

public function filterBy($accountType)

{

$filtered = [];

// 1

foreach ($this->accounts as $account) {

// 2

if ($account->type() == $accountType) {

// 3

if ($account->isActive()) {

$filtered[] = $account;

}

}

}

return $filtered;

}

}

class Account {

protected $accounts;

protected $type;

private function __construct($type)

{

$this->type = $type;

}

public function type()

{

return $this->type;

}

public function isActive()

{

return true;

}

public static function open($type)

{

return new static($type);

}

}

测试

$accounts = [

Account::open('checking'),

Account::open('savings'),

Account::open('checking'),

Account::open('savings')

];

$bankAccounts = new BankAccount($accounts);

$savings = $bankAccounts->filterBy('checking');

BankAccount 类的 filterBy 方法用于过滤账户类型,该方法包括了三层缩进。

简化一,将判断逻辑剥离出来

class BankAccount {

protected $accounts;

public function __construct($account)

{

$this->accounts = $account;

}

public function filterBy($accountType)

{

$filtered = [];

foreach ($this->accounts as $account) {

if ($this->isOfType($accountType, $account)) {

$filtered[] = $account;

}

}

}

public function isOfType($accountType, $account)

{

return $account->type() == $accountType && $account->isActive();

}

}

简化二:将判断逻辑交给子类

class BankAccounts {

public function filterBy($accountType)

{

return array_filter($this->accounts, function($account) use($accountType)

{

return $account->isOfType($accountType);

});

}

}

class Account {

public function isOfType($accountType)

{

return $this->type() == $accountType && $this->isActive();

}

}

来源:Laracasts

本作品采用《CC 协议》,转载必须注明作者和本文链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值