[英]How to inject more complex service in slim3 such as Paytrail
下面是“ Paytrail_Module_Rest.php”的示例代码,“ Paytrail_Module_Rest.php”是用于与支付网关的其他api进行交互的一组类。 某些类可以提前实例化,例如(持有凭据的Paytrail_Module_rest),但是有些类需要使用仅控制器中可用的信息实例化(例如Paytrail_Module_Rest_Payment_S1来设置付款明细,例如价格)
谁能建议将它注入slim3的干净方法? 我看不到使用标准容器注入方法执行此操作的任何好方法。
$urlset = new\App\Service\Paytrail\Paytrail_Module_Rest_Urlset(
"https://www.demoshop.com/sv/success", // return address for successful payment
"https://www.demoshop.com/sv/failure", // return address for failed payment
"https://www.demoshop.com/sv/notify", // address for payment confirmation from Paytrail server
"" // pending url not in use
);
$orderNumber = '1';
$price = 99.00;
$payment = new \App\Service\Paytrail\Paytrail_Module_Rest_Payment_S1($orderNumber, $urlset, $price);
$payment->setLocale('en_US');
$module = new \App\Service\Paytrail\Paytrail_Module_Rest(13466, '6pKF4jkv97zmqBJ3ZL8gUw5DfT2NMQ');
try {
$result = $module->processPayment($payment);
}
catch (\App\Service\Paytrail\Paytrail_Exception $e) {
die('Error in creating payment to Paytrail service:'. $e->getMessage());
}
echo $result->getUrl();
(此处列出的凭证是公共测试凭证)
将不会改变的内容添加到容器中,例如模块和urlset
$container[\App\Service\Paytrail\Paytrail_Module_Rest_Urlset::class] = function($c) {
return new \App\Service\Paytrail\Paytrail_Module_Rest_Urlset(
"https://www.demoshop.com/sv/success", // return address for successful payment
"https://www.demoshop.com/sv/failure", // return address for failed payment
"https://www.demoshop.com/sv/notify", // address for payment confirmation from Paytrail server
"" // pending url not in use
);
};
$container[\App\Service\Paytrail\Paytrail_Module_Rest::class] = function($c) {
return new \App\Service\Paytrail\Paytrail_Module_Rest(13466, '6pKF4jkv97zmqBJ3ZL8gUw5DfT2NMQ');
};
然后,您可以在每次需要时实例化付款,或添加诸如适配器之类的帮助程序类:
class PaymentAdapter {
public function __construct(
\App\Service\Paytrail\Paytrail_Module_Rest $module,
\App\Service\Paytrail\Paytrail_Module_Rest_Urlset $urlset)
{
$this->module = $module;
$this->urlset = $urlset;
}
function createAndProcessPayment($orderNumber, $price)
{
$payment = new \App\Service\Paytrail\Paytrail_Module_Rest_Payment_S1($orderNumber, $this->urlset, $price);
$payment->setLocale('en_US');
try {
$result = $module->processPayment($payment);
}
catch (\App\Service\Paytrail\Paytrail_Exception $e) {
die('Error in creating payment to Paytrail service:'. $e->getMessage());
}
return $result;
}
}
然后将适配器也添加到容器中:
$container[\yournamespace\PaymentAdapter::class] = function($c) {
return new \yournamespace\PaymentAdapter(
$c[\App\Service\Paytrail\Paytrail_Module_Rest::class],
$c[\App\Service\Paytrail\Paytrail_Module_Rest_Urlset::class]
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.