首页 > 解决方案 > 我应该如何将 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但这会导致失去灵活性......

所以我的问题是:是否有另一个好的解决方案,它也可以轻松模拟和测试?

标签: phplaravel

解决方案


推荐阅读