我正在开发自己的L5包来处理付款。为了能够在未来改变支付网关,我正在使用接口。
我的界面看起来如下:
interface BillerInterface
{
public function payCash();
public function payCreditCard();
}我也有一个具体的实现,这是理想的支付网关。
class Paypal implements BillerInterface
{
public function payCash()
{
// Logic
}
public function payCreditCard()
{
// Logic
}
}Biller类是主类,构造函数方法需要上面的接口,如下所示:
class Biller {
protected $gateway;
public function __construct(BillerInterface $gateway)
{
$this->gateway = $gateway;
}
// Logic
}最后,我创建了服务提供者,将接口绑定到网关类。
public function register()
{
$this->app->bind(BillerInterface::class, 'Vendor\Biller\Gateways\Paypal');
}似乎在工作,但我在尝试实例化Biller类时出错了.
Biller::__construct() must be an instance of Vendor\Biller\Contracts\BillerInterface, none given我试过下面的代码,但似乎不起作用.
public function register()
{
$this->app->bind(BillerInterface::class, 'Vendor\Biller\Gateways\Paypal');
$this->app->bind(Biller::class, function ($app) {
return new Biller($app->make(BillerInterface::class));
});
}有什么线索吗?
发布于 2016-05-04 21:03:09
您正在将接口绑定到服务提供程序中的实现。但依赖关系将仅由服务容器解决,即
class SomeClass
{
public function __construct(Billing $billing)
{
$this->billing = $billing;
}
}Laravel的服务容器将读取构造函数方法参数的类型提示,并解析该实例(以及它的任何依赖项)。
您将无法直接“更新”Billing实例(即$billing = new Billing),因为构造函数期望实现BillingInterface,而您没有提供这些实现。
发布于 2016-05-04 20:57:10
当将接口绑定到实际类时,尝试将BillerInterface::class替换为字符串“\you\Namespace\BillerInterface”
发布于 2016-05-04 20:58:15
这就是我在我的应用程序中所做的事情,它似乎正在起作用:
public function register()
{
$this->app->bind('DesiredInterface', function ($app) {
return new DesiredImplementationClass(
$app['em'],
new ClassMetaData(DesiredClass::class)
);
});
}https://stackoverflow.com/questions/37037486
复制相似问题