<?php
//支付接口
interface PaymentInterface {
/**支付动作
* @param array $param
* @return boolean
*/
public function pay($param = array());
}
//支付抽象类
abstract class PaymentAbstract
{
public static function usable(){
return false;
}
}
//微信支付
class WxPayment extends PaymentAbstract implements PaymentInterface {
public static function usable($param = array())
{
//如果使用微信支付
return $param == 'wx';
}
public function pay($param = array())
{
// TODO: Implement pay() method.
}
}
//支付宝支付
class AliPayment extends PaymentAbstract implements PaymentInterface {
public static function usable($param = array())
{
//如果使用支付宝支付
return $param == 'alipay';
}
public function pay($param = array())
{
// TODO: Implement pay() method.
}
}
//支付类工厂
class PaymentFactory
{
public static function getInterface($payType)
{
//写到配置文件中
$config = [
'payList' => [
WxPayment::class,
AliPayment::class
],
];
foreach($config['payList'] as $class)
{
try{
//调用各个静态方法
$isUsable = $class::usable($payType);
if($isUsable === true)
{
//如果满足这个支付类的调用条件
$payMent = new $class();
//支付类必须实现支付接口
if (!$payMent instanceof PaymentInterface)
{
throw new Exception($class.' is not instance of Payment');
}
return $payMent;
}
}catch (Exception $e)
{
echo $e->getMessage();
die;
}
}
}
}
//支付类
class Payment{
protected $payment;
public function __construct($type)
{
$this->payment = PaymentFactory::getInterface($type);
}
public function pay($data = [])
{
return $this->payment->pay($data);
}
}
//支付
(new Payment('ali'))->pay(['price'=>100.00]);