2016-03-28 6 views
0

Я использую клиент google api для загрузки файла на диск, запустил пример quickstart, указанный в google developer site, чтобы просмотреть файлы, которые работают нормально.Невозможно переопределить класс Google_Service_Drive

Чтобы вставить файл в определенную родительскую папку, я использую два объекта (см. Две строки ниже), которые вызывают ошибку, показанную ниже.

линии, которые вызывают ошибки (вторая строка вызывает ошибку):

$file = new Google_Service_Drive_DriveFile(); 
$parent = new Google_Service_Drive_ParentReference(); 

Ошибка:

PHP Fatal error: Cannot redeclare class Google_Service_Drive in C:\xampp\htdocs\driveapi\vendor\google\apiclient\src\Google\Service\Drive.php on line 729 
PHP Stack trace: 
PHP 1. {main}() C:\xampp\htdocs\driveapi\drive_client.php:0 
PHP 2. spl_autoload_call() C:\xampp\htdocs\driveapi\drive_client.php:92 
PHP 3. Composer\Autoload\ClassLoader->loadClass() C:\xampp\htdocs\driveapi\drive_client.php:92 
PHP 4. Composer\Autoload\includeFile() C:\xampp\htdocs\driveapi\vendor\composer\ClassLoader.php:301 

Полный код: (только две последние строки добавляются мной, остальное из сайт разработчика Google)

<?php require __dir__ . '/vendor/autoload.php'; 

define('APPLICATION_NAME', 'drivephp'); 
define('CREDENTIALS_PATH', '~/.credentials/drive-php-quickstart.json'); 
define('CLIENT_SECRET_PATH', __dir__ . '/client_secret.json'); 
// If modifying these scopes, delete your previously saved credentials 
// at ~/.credentials/drive-php-quickstart.json 
define('SCOPES', implode(' ', array("https://www.googleapis.com/auth/drive"))); 

if (php_sapi_name() != 'cli') { 
    throw new Exception('This application must be run on the command line.'); 
} 

/** 
* Returns an authorized API client. 
* @return Google_Client the authorized client object 
*/ 
function getClient() { 
    $client = new Google_Client(); 
    $client->setApplicationName(APPLICATION_NAME); 
    $client->setScopes(SCOPES); 
    $client->setAuthConfigFile(CLIENT_SECRET_PATH); 
    $client->setAccessType('offline'); 

    // Load previously authorized credentials from a file. 
    $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH); 
    if (file_exists($credentialsPath)) { 
     $accessToken = file_get_contents($credentialsPath); 
    } else { 
     // Request authorization from the user. 
     $authUrl = $client->createAuthUrl(); 
     printf("Open the following link in your browser:\n%s\n", $authUrl); 
     print 'Enter verification code: '; 
     $authCode = trim(fgets(STDIN)); 

     // Exchange authorization code for an access token. 
     $accessToken = $client->authenticate($authCode); 

     // Store the credentials to disk. 
     if (!file_exists(dirname($credentialsPath))) { 
      mkdir(dirname($credentialsPath), 0700, true); 
     } 
     file_put_contents($credentialsPath, $accessToken); 
     printf("Credentials saved to %s\n", $credentialsPath); 
    } 
    $client->setAccessToken($accessToken); 

    // Refresh the token if it's expired. 
    if ($client->isAccessTokenExpired()) { 
     $client->refreshToken($client->getRefreshToken()); 
     file_put_contents($credentialsPath, $client->getAccessToken()); 
    } 
    return $client; 
} 

/** 
* Expands the home directory alias '~' to the full path. 
* @param string $path the path to expand. 
* @return string the expanded path. 
*/ 
function expandHomeDirectory($path) { 
    $homeDirectory = getenv('HOME'); 
    if (empty($homeDirectory)) { 
     $homeDirectory = getenv("HOMEDRIVE") . getenv("HOMEPATH"); 
    } 
    return str_replace('~', realpath($homeDirectory), $path); 
} 

// Get the API client and construct the service object. 
$client = getClient(); 
$service = new Google_Service_Drive($client); 
$parentId = null; 

// Print the names and IDs for up to 10 files. 
$optParams = array(
//  'pageSize' => 10, 'fields' => 
//  "nextPageToken, files(id, name)" 
); 
$results = $service->files->listFiles($optParams); 

if (count($results->getFiles()) == 0) { 
    print "No files found.\n"; 
} else { 
    print "Files:\n"; 
    foreach ($results->getFiles() as $file) { 
     printf("%s (%s)\n", $file->getName(), $file->getId()); 
    } 
} 

$file = new Google_Service_Drive_DriveFile(); 
$parent = new Google_Service_Drive_ParentReference(); 

?> 

Пожалуйста, помогите.

ответ

0

avil, я предполагаю, что вы столкнулись с тем же вопросом, с которым я столкнулся. Я последовал за «QuickStart» инструкции на этой странице:

https://developers.google.com/drive/v3/web/quickstart/php#prerequisites

установить AppClient: 1. * используя композитор и затем говорит:

«скачать и распаковать этот почтовый файл и скопировать диск .php поставщику/google/apiclient/src/Google/Service /, заменив существующий файл. "

Я получил ту же ошибку и стал подозрительным, так что я проверил на GIT и посмотрел на историю этого файла:

https://github.com/google/google-api-php-client/blob/v1-master/src/Google/Service/Drive.php

Вы заметите, что «v1-мастер» версии Диска. php составляет почти 2000 строк кода короче, чем предыдущий выпуск в октябре 2015 года.

Весь код для вашего «Google_Service_Drive_ParentReference» (я искал класс Google_Service_Drive_Property) отсутствует в новейшей версии.

Я буквально скопировал код из истории репозитория GIT (9 октября 2015 года) в свой файл Drive.php, и теперь он отлично работает.

Надеюсь, это поможет,

+0

Привет, Большое спасибо за помощь. Я загрузил более старую версию Drive.php и мне пришлось изменить пару функций, таких как (getFiles -> getItems и setName -> setTitle и т. Д.), Но в итоге она работала хорошо. – avil

Смежные вопросы