如何将IOC容器与使用其他依赖项的依赖项一起使用?

时间:2019-04-06 06:52:02

标签: php laravel

我目前正在重构代码,以验证我的App后端的Google Play应用内购买交易,而且我不确定初始化Google SDK提供的类的最佳解决方案是什么。

我正在使用Google提供的SDK: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容器的调用替换 new 调用,但是我的问题是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,但这会导致灵活性丧失...

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

0 个答案:

没有答案