【问题标题】:How to integrate the PHP client for the Google API with Symfony 2?如何将 Google API 的 PHP 客户端与 Symfony 2 集成?
【发布时间】:2016-08-05 18:36:46
【问题描述】:

我使用google-api-php-client 创建了一个PHP 应用程序。我从 Google 控制台创建了一个 Google 帐户电子邮件 ID,从那里生成了 P12 文件,并将其放入本地服务器。这适用于“自定义”PHP。

现在我想将 google-api-php-client 库与我的 Symfony 项目集成到一个自定义包中。我在/app/Resources 中创建了一个文件夹“LIB”,并将google-api-php-client 的所有文件都放在那里。

然后我将下面的行放在主控制器中以包含autoload.php 文件并访问Google_Client 类:

//require_once($this->container->getParameter( 'kernel.root_dir' ). '/../src/ABC/Bundle/TTBundle/Lib/src/Google/autoload.php');
$service_account_email = 'xxxxx-yyyyyy@developer.gserviceaccount.com';
$key_file_location = 'API-Project.p12';

// Create and configure a new client object.
$client = new Google_Client();

但它显示了以下错误:

FatalErrorException:错误:类 'ABC\Bundle\TTBundle\Controller\Google_Client' 未在 D:\wamp\www\TTPR\current\src\ABC\Bundle\TTBundle\Controller\WebAnalyticsController.php 第 133 行

【问题讨论】:

  • 你必须给它命名空间并让 symfony2 自动加载那个类
  • 不能在控制器函数中加载那个类吗?
  • 是的,但您需要“指导”(自动加载)框架
  • 感谢您的回复,能否请您编写创建命名空间和自动加载的步骤,这对初学者非常有帮助,我现在想要在 (current/app/Resources) 中创建一个文件夹“LIB”在此路径中包含文件 --> autoload.php: require_once($this->container->getParameter( 'kernel.root_dir' ). '/../src/MWAN/Bundle/BIBundle/Lib/src/Google/ autoload.php' 并想在控制器中使用它。我会很感激你的帮助

标签: php symfony google-analytics-api google-api-php-client


【解决方案1】:

我通过以下步骤解决了这个问题:

1- 在我的控制器中创建一个函数:

2- 在 getService 函数中,我调用了我自己创建的函数来包含 autoload.php 文件:

需要知道的重要事情是在创建 CLASS 对象时放置一个“反斜杠”(/),我错过了这个“反斜杠”并浪费了我的时间,希望这会有所帮助并节省时间 :)

protected function includeSsrsSdk()
    {
          require_once($this->container->getParameter( 'kernel.root_dir' ). '/../src/MWAN/Bundle/BIBundle/Lib/src/Google/autoload.php');

    }



public function getService()
    {


      $this->includeSsrsSdk();
      $service_account_email = 'xxyyzz@developer.gserviceaccount.com';
      $key_file_location = $this->container->getParameter( 'kernel.root_dir' ). '/../src/MWAN/Bundle/BIBundle/Lib/API-Project-xxxx.p12';

      // Create and configure a new client object.
      $client = new \Google_Client();
      $client->setApplicationName("HelloAnalytics");
      $analytics = new \Google_Service_Analytics($client);

      // Read the generated client_secrets.p12 key.
      $key = file_get_contents($key_file_location);
      $cred = new \Google_Auth_AssertionCredentials(
          $service_account_email,
          array(\Google_Service_Analytics::ANALYTICS_READONLY),
          $key
      );
      $client->setAssertionCredentials($cred);
      if($client->getAuth()->isAccessTokenExpired()) {
        $client->getAuth()->refreshTokenWithAssertion($cred);
      }

      return $analytics;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-02
    • 1970-01-01
    • 1970-01-01
    • 2018-01-13
    • 1970-01-01
    • 2020-09-23
    相关资源
    最近更新 更多