我会将代码最小化为您需要查看的内容。
我有 3 个课程Customer
:Courier
和Order
。
class Customer extends AbstractRegisteredUser implements CustomerInterface {
}
class Courier extends AbstractRegisteredUser implements CourierInterface {
}
class Order extends AbstractEntity implements OrderInterface {
private $customer;
private $courier;
public function isUserAssociated(RegisteredUserInterface $user) {
switch( $user->GetEntityType() ) {
case 'Customer':
return $this->isCustomerAssociated($user);
case 'Courier':
return $this->isCourierAssociated($user);
}
return false;
}
private function isCustomerAssociated(CustomerInterface $customer) {
return ( $this->customer->getId() === $customer->getId() );
}
private function isCourierAssociated(CourierInterface $courier) {
return ( $this->courier->getId() === $courier->getId() );
}
}
正如你所看到的,我在那里有一个 switch 语句,我不想有,所以我想出了这样的做法:
class Customer extends AbstractRegisteredUser implements CustomerInterface {
public function isAssociatedWithOrder(OrderInterface $order) {
return ( $this->getId() === $order->getCustomerId() );
}
}
class Courier extends AbstractRegisteredUser implements CourierInterface {
public function isAssociatedWithOrder(OrderInterface $order) {
return ( $this->getId() === $order->getCourierId() );
}
}
我现在可以从类中删除isUserAssociated
,isCustomerAssociated
和isCourierAssociated
方法Order
以及丑陋的 switch 语句。
现在,当我想检查客户是否与给定订单相关联时,我会
// $user could be a customer or courier object.
if( !$user->isAssociatedWithOrder($order) ) {
}
代替
if( !$order->isUserAssociated($customer) ) {
}
这是一个需要更少代码、更少方法并且更容易使用的解决方案,但这样做是否正确?Customer
和类不应该Courier
知道Order
吗?这是否会被认为将责任赋予不应承担该责任的班级?
任何帮助都会非常感谢。