我有一个具有以下功能的控制器
public function completeRegistration(Request $request)
{
$yy = $request->exp_year;
$mm = $request->exp_month;
$cardnum = $request->cardnum;
$cvc = $request->cvc;
}
我希望能够做到这样的事情
public function completeRegistration(Request $request)
{
$yy = $request->exp_year;
$mm = $request->exp_month;
$cardnum = $request->cardnum;
$cvc = $request->cvc;
if(billUser($cardnum, $mm, $yy, $cvc))
{
echo "charge success";
}
else
{
echo "uh something was wrong";
}
}
自从5.2不再拥有命令和处理程序后,我的选择是什么?其他控制器需要能够与我的支付网关的API进行交互。我需要一个与支付相关的功能列表,我可以轻松地将其调用到任何控制器中。
答案 0 :(得分:1)
我认为您需要提供服务:
# app/Services/Payment/Payment.php
<?php
namespace App\Services\Payment;
class Payment
{
public function billUser($cardnum, $mm, $yy, $cvc)
{
// Your logic here
}
}
然后,如果您想要将此服务“Laravel方式”集成,则需要创建服务提供商:
# app/Services/Payment/PaymentServiceProvider.php
<?php
namespace App\Services\Payment;
use Illuminate\Support\ServiceProvider;
class PaymentServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->singleton('Payment', function($app) {
return new Payment();
});
}
}
然后在config/app.php
注册此服务提供商:
return [
...
'providers' => [
...
App\Services\Payment\PaymentServiceProvider::class,
...
],
...
];
然后,您可以在控制器中访问它:
<?php
namespace App\Http\Controllers;
public function completeRegistration(Request $request)
{
$yy = $request->exp_year;
$mm = $request->exp_month;
$cardnum = $request->cardnum;
$cvc = $request->cvc;
if(app('Payment')->billUser($cardnum, $mm, $yy, $cvc))
{
echo "charge success";
}
else
{
echo "uh something was wrong";
}
}
然后,您可以进一步为您的服务创建Facade:
# app/Services/Payment/PaymentFacade.php
<?php
namespace App\Services\Payment;
use Illuminate\Support\Facades\Facade;
class PaymentFacade extends Facade
{
protected static function getFacadeAccessor()
{
return 'Payment';
}
}
要使用它,您还需要将其注册到app/config.php
文件中:
return [
...
'aliases' => [
....
'Payment' => App\Services\Payment\PaymentFacade::class,
],
];
并在代码中的任何位置使用它:
<?php
namespace App\Http\Controllers;
use Payment;
public function completeRegistration(Request $request)
{
$yy = $request->exp_year;
$mm = $request->exp_month;
$cardnum = $request->cardnum;
$cvc = $request->cvc;
if(Payment::billUser($cardnum, $mm, $yy, $cvc))
{
echo "charge success";
}
else
{
echo "uh something was wrong";
}
}
我希望这有帮助!