详细的注解
整理了放在这里 方便 CTRL+V
<?php
// 定义PaymentMethod接口
interface PaymentMethod {
public function processPayment();
}
// 实现PaymentBase类,该类为基类实现接口检测
abstract class PaymentBase implements PaymentMethod{
protected $config;
protected $order;
public function __construct($config) {
$this->config = $config;
}
public function __call($method,$args){
if (!method_exists($this, $method)) {
$className = get_class($this);
throw new Exception("Class '$className' Method '$method' does not exist.");
}
// 如果方法存在,则调用该方法并传递参数
return call_user_func_array([$this, $method], $args);
}
public function __set($name, $val){
$this->$name = $val;
}
}
// 实现CreditCardPayment类,该类实现PaymentMethod接口
class CreditCardPayment extends PaymentBase {
public function processPayment() {
// 使用初始化时传入的配置文件进行信用卡支付操作...
echo "处理信用卡支付...".json_encode($this->config);
}
}
// 实现PayPalPayment类,该类实现PaymentMethod接口
class PayPalPayment extends PaymentBase {
public function processPayment() {
// 使用初始化时传入的配置文件进行PayPal支付操作...
echo "处理PayPal支付...".json_encode($this->config).json_encode($this->order);
}
}
// 定义PaymentFactory类,用于创建支付方式对象
class PaymentFactory {
// 创建指定类型的支付方式对象
public static function createPaymentMethod($type, $config = []) {
// 检查支付方式类型是否存在对应的支付方式类
if (!class_exists($type)) {
throw new Exception("无效的支付方式类型。无效的支付类。");
}
// 获取支付方式类的反射对象
$paymentClass = new \ReflectionClass($type);
// 创建支付方式对象并使用传入的配置文件进行初始化
$payment = $paymentClass->newInstance($config); // 使用传入的配置文件进行初始化
return $payment; // 返回初始化的支付方式对象给调用者使用
}
}
// 使用示例
try {
// 创建信用卡支付方式对象,并调用processPayment方法,不传入配置文件,由工厂方法自动加载配置文件进行初始化。
$creditCardPayment = PaymentFactory::createPaymentMethod('CreditCardPayment',['name'=>'pay1']);
// 执行信用卡支付操作,输出: 处理信用卡支付...
$creditCardPayment->processPayment(); // 输出: 处理信用卡支付...
// 创建PayPal支付方式对象,并调用processPayment方法,不传入配置文件,由工厂方法自动加载配置文件进行初始化。
$payPalPayment = PaymentFactory::createPaymentMethod('PayPalPayment',['name'=>'pay2']);
$payPalPayment->order=['id'=>'abc'];
// 执行PayPal支付操作,输出: 处理PayPal支付...
$payPalPayment->processPayment(); // 输出: 处理PayPal支付...
} catch (Exception $e) {
echo "发生错误: " . $e->getMessage();
}