我和收银员一起使用Laravel4.2,我需要修改它的受保护函数buildPayload(),但是我不想直接在供应商文件中这样做,因为当我编写器更新时我可能会破坏代码.我应该如何用我自己的逻辑来重写这个函数?
目前,我在我的一个控制器中使用收银机,方法是:
$user->subscription('testplan')
->create(Input::get('stripeToken'), [
'email' => 'email@email.com,
]);
但是我想添加一个withTax()参数..。就像这样:
$user->subscription('testplan')
->withTax(10)
->create(Input::get('stripeToken'), [
'email' => 'email@email.com,
]);
我已经知道如何在StripeGateway.php
文件中直接做这件事了,但这是错误的做法.
我知道我需要补充:
protected $taxPercent = 0;
public function withTax($tax)
{
$this->taxPercent = $tax;
return $this;
}
protected function buildPayload()
{
$payload = [
'plan' => $this->plan, 'prorate' => $this->prorate,
'quantity' => $this->quantity, 'trial_end' => $this->getTrialEndForUpdate(),
'tax_percent' => $this->taxPercent,
];
return $payload;
}
我不知道的是如何添加这些代码,而不是直接在收银机原始文件中添加。
发布于 2015-08-30 15:07:14
我自己想出了办法,这是我第一次做这种事.如果我的方法错了,请纠正我!
第一:
我创建了一个名为laravel/app/Lib/Cashier的文件夹,名为Lib\
然后我创建了两个文件:BillableTrait.php和NewStripeGateway.php
BillableTrait.php代码:
<?php namespace Lib\Cashier;
use Laravel\Cashier;
use Lib\Cashier\NewStripeGateway as StripeGateway;
trait BillableTrait {
use Cashier\BillableTrait;
/**
* Get a new billing gateway instance for the given plan.
*
* @param \Laravel\Cashier\PlanInterface|string|null $plan
* @return \Laravel\Cashier\StripeGateway
*/
public function subscription($plan = null)
{
if ($plan instanceof PlanInterface) $plan = $plan->getStripeId();
return new StripeGateway($this, $plan);
}
}
对于NewStripeGateway.php
<?php namespace Lib\Cashier;
use Laravel\Cashier\StripeGateway;
class NewStripeGateway extends StripeGateway {
protected $taxPercent = 0;
public function withTax($tax)
{
$this->taxPercent = $tax;
return $this;
}
protected function buildPayload()
{
$payload = [
'plan' => $this->plan, 'prorate' => $this->prorate,
'quantity' => $this->quantity, 'trial_end' => $this->getTrialEndForUpdate(),
'tax_percent' => $this->taxPercent,
];
return $payload;
}
}
然后,我编辑了使用类似收银机的模型(只更改了use块):
use Lib\Cashier\BillableTrait;
use Laravel\Cashier\BillableInterface;
我现在可以直接这样做来设置订阅的税收:
$user->subscription('testplan')
->withTax(10)
->create(Input::get('stripeToken'), [
'email' => 'email@email.com',
]);
它工作得很好!!如果我做错了什么,请注意更改,这是我第一次自己挖掘PHP类(特性、扩展等)。
谢谢!
拉斐尔
发布于 2015-08-30 09:38:55
您可以在您的getTaxPercent
模型中添加user
方法,它也将计算税收。
遗憾的是,没有办法扩展StripeGateway
类,因为它在Billable
特性中进行了硬编码,您可以做的就是更改这些函数-
在您的public function charge($amount, array $options = []) { return (new StripeGateway($this))->charge($amount, $options); } public function subscription($plan = null) { return new StripeGateway($this, $plan); }
类中,这里的问题是您永远不可能知道Billable
中会发生什么变化,它们可能会更改函数的名称,并添加少量使用StripeGateway
的函数,直到bug出现时,您才会知道。
第一个选项可能要好得多,因为您不需要每次都提到withTax
方法。
https://stackoverflow.com/questions/32298744
复制相似问题