php - 我应该如何将 IOC 容器与使用其他依赖项的依赖项一起使用?
问题描述
我目前正在重构我的代码,以验证我的应用程序后端的 Google Play In App Purchases,但我不确定初始化 Google SDK 提供的类的最佳解决方案是什么。
我正在使用的 Google 开发工具包:https ://github.com/googleapis/google-api-php-client
对于验证我正在使用这个作曲家包:https ://github.com/aporat/store-receipt-validator
我之前的代码:
class GooglePlayIAPService extends InAppPurchaseService
{
public function __construct(UserService $userService)
{
parent::__construct($userService);
$googleClient = new \Google_Client();
$googleClient->setScopes([\Google_Service_AndroidPublisher::ANDROIDPUBLISHER]);
$googleClient->setApplicationName('My app name');
$googleClient->setAuthConfig(config('app.iap_service_credentials.google'));
$googleAndroidPublisher = new \Google_Service_AndroidPublisher($googleClient);
$this->googleValidator = new \ReceiptValidator\GooglePlay\Validator($googleAndroidPublisher);
}
/* The validation functions... */
}
我想用对 IOC 容器的调用替换新调用,但我的问题是Google_Service_AndroidPublisher
需要一个已初始化的Google_Client
. 我的方法是使用App::makeWith(...)
,但我对这个解决方案不太满意......
class GooglePlayIAPService extends InAppPurchaseService
{
public function __construct(UserService $userService, Google_Client $googleClient)
{
parent::__construct($userService);
$googleClient->setScopes([\Google_Service_AndroidPublisher::ANDROIDPUBLISHER]);
$googleClient->setApplicationName('My app name');
$googleClient->setAuthConfig(config('app.iap_service_credentials.google'));
$googleAndroidPublisher = App::makeWith(Google_Service_AndroidPublisher::class, ['googleClient' => $googleClient]);
$this->googleValidator = App::makeWith(GoogleValidator::class, ['googleServiceAndroidPublisher' => $googleAndroidPublisher]);
}
/* Validation functions */
}
或者,另一种方法可能是Google_Client
完全初始化,AppServiceProvider
但这会导致失去灵活性......
所以我的问题是:是否有另一个好的解决方案,它也可以轻松模拟和测试?
解决方案
推荐阅读
- python - Beautifulsoup / Selenium如何抓取网站直到下一页被禁用?
- python - GLSL,基于 SDF 的圆角矩形
- java - 使用比较器按预定义的优先级顺序排序
- javascript - 如何将 d3 树布局从顶部翻转到底部顶部并调整大小以在不同设备上看起来不错
- android - genymotion界面倒置
- java - 我尝试从服务器(python)发送列表长度并发送列表项并由客户端(java)使用套接字 IO 接收它
- django - 不断得到这个:TypeError:元类冲突:派生类的元类必须是其所有基类的元类的(非严格)子类
- c++ - 如何在 C++ 中将指针数组传递给函数模板
- python - 在 Python 中为两个排序列表合并排序算法 - 构造 for 循环的麻烦
- javascript - Webpack:从javascript内部获取块列表