【发布时间】:2019-03-07 09:50:06
【问题描述】:
我有以下结构使用Open Close Principle
class Payment{
//this is not a model class
// according to OC principle this class should not focus on the implementation
private $paymentInterface;
public function __construct(PaymentInterface $paymentInterface)
{
$this->paymentInterface = $paymentInterface;
}
//so store method does not know which implementation it will get
public function store($request,$id)
{
return $this->paymentInterface->store($request,$id);
}
}
界面
interface PaymentInterface{
public function store($request,$id = null);
}
包含实现的支付服务类
class PaymentService implements PaymentInterface{
public function store($request,$id = null){
//payment store logic is here
}
}
控制器
class PaymentsController extends Controller{
protected $payment;
public function __construct()
{
$this->payment = new Payment(new PaymentService);
}
public function storePayment(PaymentRequest $request, $id)
{
try {
$response = $this->payment->store($request,$id);
return redirect()->route($this->route.'.index')->with($response['status'],$response['message']);
} catch (\Exception $e) {
return $this->vendorDashboard($e);
}
}
}
我的问题是: 使用 Open-Close-Principle 是否正确? 使用上面的代码,我可以告诉控制器我可以使用 PaymentService 类来实现。
$payment = new Payment(new PaymentService);
return $payment->store($request,$id);
如果以后我想以其他方式付款,例如通过发票付款,然后我可以创建新控制器,在新类中编写新实现,例如InvoicePaymentService 并告诉 Payment 类使用 InvoicePaymentService 作为实现
$payment = new Payment(new InvoicePaymentService);
return $payment->store($request,$id);
或
$payment = new Payment(new PayPalPaymentService);
return $payment->store($request,$id);
或
$payment = new Payment(new AliPayPaymentService);
return $payment->store($request,$id);
我知道我可以通过服务提供者将接口与类绑定,但如果我想实现不同的支付实现,那么我将无法更改类,对吧?
如果我做错了,请告诉我。
【问题讨论】:
-
“但是如果我想实现不同的支付实现” - 你的意思是不同的支付类实现吗?
-
是的。我在问题中提到过。就像我想用 PayPal 或支付宝付款一样
标签: php laravel solid-principles open-closed-principle