Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Apiclient Services Laravel Package

google/apiclient-services

Auto-generated Google API service definitions for the Google API PHP Client. Updated daily to reflect API changes and tagged weekly. Install via Composer with google/apiclient to access many Google services from PHP.

View on GitHub
Deep Wiki
Context7

Getting Started

  1. Installation: Add google/apiclient to composer.json (transitively pulls google/apiclient-services):

    composer require google/apiclient:^2.15
    

    Verify the correct service classes are autoloaded via composer dump-autoload.

  2. First Use Case: Authenticate and list Drive files:

    use Google\Client;
    use Google\Service\Drive;
    
    $client = (new Client())
        ->setApplicationName('MyApp')
        ->setAuthConfig(storage_path('app/google-credentials.json'))
        ->addScope(Drive::DRIVE);
    
    $drive = new Drive($client);
    $files = $drive->files->listFiles(['pageSize' => 10])->getFiles();
    

    Store credentials in .env or Laravel config (e.g., config('services.google.credentials')).

  3. Laravel Integration: Use config('services.google') for credentials and bind the client in a service provider:

    $this->app->singleton(Drive::class, function ($app) {
        $client = new Client();
        $client->setAuthConfig($app['config']['services.google.credentials']);
        return new Drive($client);
    });
    

Implementation Patterns

Service Provider Pattern

Wrap Google clients in Laravel’s IoC container for dependency injection:

// app/Providers/GoogleServiceProvider.php
public function register()
{
    $this->app->singleton(Google\Client::class, function ($app) {
        $client = new Google\Client();
        $client->setApplicationName(config('app.name'));
        $client->setAuthConfig(config('services.google.credentials'));
        return $client;
    });

    $this->app->bind(Google\Service\Drive::class, function ($app) {
        return new Google\Service\Drive($app->make(Google\Client::class));
    });
}

Job Queues for Batch Operations

Offload heavy operations (e.g., bulk file uploads) to Laravel queues:

// app/Jobs/SyncDriveFiles.php
public function handle()
{
    $batch = new Google\Http\Batch($this->client);
    foreach ($this->files as $file) {
        $batch->add($this->drive->files->create($file));
    }
    $batch->execute(); // Handles partial failures
}

Pagination Helper

Abstract pagination logic into a reusable trait or service:

// app/Services/GooglePaginator.php
public function paginate($service, $method, array $params = [])
{
    do {
        $response = $service->$method($params);
        yield from $response->getItems();
        $params['pageToken'] = $response->getNextPageToken();
    } while ($params['pageToken']);
}

Event-Driven Syncs

Trigger Google API calls on Laravel events (e.g., user.created):

// app/Listeners/SyncGoogleCalendar.php
public function handle(UserCreated $event)
{
    $calendar = app(Google\Service\Calendar::class);
    $event = new Google\Service\Calendar\Event([
        'summary' => 'Welcome: ' . $event->user->name,
    ]);
    $calendar->events->insert('primary', $event);
}

Scopes Management

Dynamically assign scopes per request to reduce memory usage:

// app/Http/Controllers/GoogleController.php
public function upload(UploadRequest $request)
{
    $client = app(Google\Client::class);
    $client->addScope(Google\Service\Drive::DRIVE); // Only for this request
    $drive = new Google\Service\Drive($client);
    // ...
}

Gotchas and Tips

Critical Pitfalls

  1. Version Conflicts:

    • Never install google/apiclient-services directly. Always use google/apiclient as the root dependency.
    • Fix: Run composer why-not google/apiclient-services to debug conflicts.
  2. Memory Bloat:

    • Loading unused service classes (e.g., Google\Service\Sheets + Google\Service\Calendar) consumes 10–50MB per class.
    • Fix: Use Google\Client::setScopes() sparingly or lazy-load clients.
  3. Token Expiry:

    • Refresh tokens silently fail if not handled. Use Google\Client::fetchAccessTokenWithRefreshToken() in middleware:
      if ($client->isAccessTokenExpired()) {
          $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
      }
      
  4. API Quotas:

    • Google returns 429 (quota exceeded) or 503 (server overload). Implement exponential backoff:
      try {
          $response = $drive->files->create($file);
      } catch (Google\Service\Exception $e) {
          if ($e->getCode() === 429) {
              sleep(2); // Retry after delay
              retry();
          }
          throw $e;
      }
      

Debugging Tips

  1. Enable Logging:

    $client->setLogger(app(\Psr\Log\LoggerInterface::class));
    

    Check logs for http_request and http_response entries.

  2. Inspect Raw Responses:

    $response = $drive->files->listFiles();
    \Log::debug($response->getRawContent());
    
  3. Common Errors:

    • 403: Access Denied: Verify scopes (Google\Service\Drive::DRIVE vs. Google\Service\Drive::DRIVE_METADATA_READONLY).
    • 400: Invalid JSON: Sanitize payloads (e.g., json_encode($data, JSON_UNESCAPED_UNICODE)).

Performance Optimizations

  1. Batch Requests:

    • Use Google\Http\Batch for >100 operations (reduces HTTP overhead by 80%).
    • Example: Bulk file updates in a single request.
  2. Caching Responses:

    • Cache paginated results (TTL: 5–10 minutes):
      return Cache::remember("drive-files-{$userId}", 600, function () use ($drive) {
          return iterator_to_array($this->paginate($drive->files, 'listFiles'));
      });
      
  3. Async Processing:

    • For long-running tasks, use Laravel Horizon + Google\Service\Drive::files->create() in a job.

Extension Points

  1. Custom HTTP Client:

    • Replace the default HTTP client with Guzzle for middleware (e.g., retries):
      $client->setHttpClient(new \GuzzleHttp\Client([
          'timeout' => 30,
          'connect_timeout' => 5,
      ]));
      
  2. Service Decorators:

    • Extend auto-generated services (e.g., add soft-delete logic):
      class CustomDrive extends Google\Service\Drive {
          public function softDelete($fileId) {
              $file = $this->files->get($fileId);
              $file->setTrashed(true);
              return $this->files->update($fileId, $file);
          }
      }
      
  3. Webhook Integration:

    • Use Google\Service\Drive::changes->watch() to listen for file changes and dispatch Laravel events.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport