试图增加我的PHP / Laravel知识,所以在创建新功能时,我尝试使用接口进行工作。
为了设置场景:我们公司在一年内几次更改了直接借记提供商,我希望创建这个接口以使未来的更改更加“脚手架化”。
我的代码结构:
应用程序\接口\DirectDebitInterface
interface DirectDebitInterface {
    public function createAccount($account);
    // additional methods
}
应用\服务\DirectDebit\Clients\Bottomline
class Bottomline implements DirectDebitInterface {
    public function getAccount(String $reference)
    {
        // do external API call, return back data
    }
}
App\Providers\AppServiceProvider @register
$this->app->bind(
    DirectDebitInterface::class,
    config('services.direct_debit_clients.' . // Bottomline
    config('services.direct_debit_clients.default') . '.class') // App\Services\DirectDebit\Clients\Bottomline::class
);
我的当前用法是有效的,但感觉不正确,这是一个使用getAccount()方法的测试端点:
public function getAccount(DirectDebitInterface $directDebitInterface)
{
    dd($directDebitInterface->getAccount('OS10129676'));
}
我的第一个问题是,我从来没有见过有人在类的变量设置中使用接口?
我的第二个问题是,我正在使用Livewire加载数据,但无法弄清楚如何使用接口。
这是我第二个问题的示例代码:
App\Http\Livewire\示例
public function mount(Account $account)
{
    self::getDirectDebitAccount();
}
private function getDirectDebitAccount(DirectDebitInterface $directDebitInterface)
{
    dd($directDebitInterface->getAccount($reference));
}
上述代码失败,因为该方法需要传入一个参数,但我也不能实例化该类,因为它是一个接口。
除了感觉我的知识中存在一些基本差距之外...似乎我走在正确的轨道上,但我对类/接口的使用设置不正确。
对于如何从方法内部调用此接口或者在某些地方出错的任何建议?
那里,
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
你正在进行基于方法的依赖注入,这是完全有效的,但可以说比构造函数的依赖注入更少见。两者都有相似的结果,即注入所需的依赖项,主要区别在于依赖项的范围(方法 vs 类)。
在标准的Laravel/PHP环境中,构造函数注入可能如下所示:
private DirectDebitInterface $directDebitor; public function __construct(DirectDebitInterface $directDebitor) { $this->directDebitor = $directDebitor; } public function doSomething(string $account) { dd($this->directDebitor->getAccount($account)); }Livewire略有不同,因为你不使用
__construct函数在Component中,而是需要使用mount()函数。public function mount(DirectDebitInterface $directDebitor) { $this->directDebitor = $directDebitor; }假设你已经在
bindings中正确配置了服务容器,一切应该工作正常。