Installation Add the bundle via Composer:
composer require cekurte/google-api-bundle
Enable the bundle in config/bundles.php:
return [
// ...
Cekurte\GoogleApiBundle\CekurteGoogleApiBundle::class => ['all' => true],
];
Configuration Publish the default configuration:
php bin/console cekurte:google-api:install
Update config/packages/cekurte_google_api.yaml with your Google API credentials (e.g., OAuth 2.0 client ID/secret, service account key).
First Use Case Use the bundle to interact with a Google API (e.g., Google Sheets):
use Cekurte\GoogleApiBundle\Service\GoogleApiService;
class MyController extends AbstractController
{
public function __construct(private GoogleApiService $googleApiService) {}
public function index()
{
$client = $this->googleApiService->getClient('sheets', 'v4');
$service = new Google_Service_Sheets($client);
$spreadsheet = $service->spreadsheets->get('spreadsheetId');
return $this->json($spreadsheet);
}
}
Resources/doc/index.md for setup and API usage.config/packages/cekurte_google_api.yaml for bundle settings.GoogleApiService to instantiate Google API clients.Service Initialization The bundle provides a centralized way to create Google API clients:
// Get a client for a specific API (e.g., Sheets, Drive, Calendar)
$client = $this->googleApiService->getClient('sheets', 'v4');
$service = new Google_Service_Sheets($client);
Authentication Workflows
config/packages/cekurte_google_api.yaml and use the bundle to handle user authentication flows.
cekurte_google_api:
auth:
oauth:
client_id: '%env(GOOGLE_OAUTH_CLIENT_ID)%'
client_secret: '%env(GOOGLE_OAUTH_CLIENT_SECRET)%'
redirect_uri: '%env(GOOGLE_OAUTH_REDIRECT_URI)%'
cekurte_google_api:
auth:
service_account:
key_file: '%kernel.project_dir%/config/google-service-account.json'
API Calls
Use the generated Google API service classes (e.g., Google_Service_Sheets) to interact with endpoints:
$result = $service->spreadsheets->get('spreadsheetId');
$batchUpdate = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest();
$batchUpdate->setRequests([/* ... */]);
$updatedSpreadsheet = $service->spreadsheets->batchUpdate('spreadsheetId', $batchUpdate);
Dependency Injection
Inject GoogleApiService into controllers, services, or commands to reuse client initialization logic.
User Authentication Flow Redirect users to Google for OAuth authorization:
$authUrl = $this->googleApiService->getAuthUrl('sheets', 'https://example.com/callback');
return $this->redirect($authUrl);
Handle the callback to exchange the authorization code for tokens:
$token = $this->googleApiService->handleAuthCallback('sheets', $code);
Batch Operations Use the bundle to handle token refreshes and batch API calls efficiently:
$client = $this->googleApiService->getClient('sheets', 'v4');
$client->setUseBatch(true);
Error Handling Wrap API calls in try-catch blocks to handle Google API exceptions:
try {
$result = $service->spreadsheets->get('spreadsheetId');
} catch (Google_Service_Exception $e) {
// Handle API-specific errors (e.g., 404 for non-existent resources)
$this->addFlash('error', $e->getMessage());
} catch (Google_Auth_Exception $e) {
// Handle authentication errors
$this->addFlash('error', 'Authentication failed');
}
Environment Variables
Store sensitive credentials (e.g., OAuth client secrets, service account keys) in .env:
GOOGLE_OAUTH_CLIENT_ID=your_client_id
GOOGLE_OAUTH_CLIENT_SECRET=your_client_secret
GOOGLE_SERVICE_ACCOUNT_KEY=%kernel.project_dir%/config/google-service-account.json
Caching Clients Reuse clients for performance (the bundle manages client lifecycle):
// Reuse the same client for multiple calls
$client = $this->googleApiService->getClient('sheets', 'v4');
$service->spreadsheets->get('spreadsheetId1');
$service->spreadsheets->get('spreadsheetId2');
Custom API Services Extend the bundle to support custom Google APIs not covered by default:
# config/packages/cekurte_google_api.yaml
cekurte_google_api:
apis:
custom_api:
version: 'v1'
class: Google_Service_CustomApi
Deprecated APIs The bundle may not support the latest Google API versions. Verify compatibility with the Google API PHP Client library.
Service Account Scopes Ensure your service account key has the correct scopes for the API you’re using. For example, for Google Sheets:
cekurte_google_api:
auth:
service_account:
scopes: ['https://www.googleapis.com/auth/spreadsheets']
Token Expiry OAuth tokens expire. Handle token refreshes gracefully:
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
}
Locale/Encoding Issues Google APIs may return data in UTF-8 or other encodings. Normalize responses:
$response = mb_convert_encoding($response, 'UTF-8', 'auto');
Bundle Maturity The bundle has low activity (0 stars, no dependents). Test thoroughly in a staging environment before production use.
Enable Debugging Enable Google API client logging to debug issues:
$client->setDeveloperKey('your_api_key');
$client->setApplicationName('MyApp/1.0');
$client->setDebug(true);
$client->setAccessType('offline');
Check HTTP Requests Use tools like Postman or browser dev tools to inspect raw API requests/responses.
Symfony Profiler
Use Symfony’s profiler to inspect the GoogleApiService calls and debug performance bottlenecks.
Default API Configuration
The bundle assumes default API configurations (e.g., Sheets API uses v4). Override in config/packages/cekurte_google_api.yaml:
cekurte_google_api:
apis:
sheets:
version: 'v4'
class: Google_Service_Sheets
Auth Provider Switching The bundle supports both OAuth and service accounts. Ensure your config matches the auth method:
# OAuth example
cekurte_google_api:
auth:
oauth:
enabled: true
service_account: false
# Service account example
cekurte_google_api:
auth:
oauth:
enabled: false
service_account:
enabled: true
Custom Client Factories Extend the bundle to support custom client initialization logic:
// src/Service/CustomGoogleApiService.php
use Cekurte\GoogleApiBundle\Service\GoogleApiService;
class CustomGoogleApiService extends GoogleApiService
{
public function getCustomClient()
{
$client = $this->createClient('custom_api', 'v1');
// Customize client here
return $client;
}
}
Event Listeners
Listen to bundle events (e.g., google_api.client.created) to intercept client creation:
// src/EventListener/GoogleApiListener.php
use
How can I help you explore Laravel packages today?