Install the Bundle Add the package via Composer:
composer require appventus/avbitly-bundle
Enable the bundle in config/bundles.php:
return [
// ...
AppVentus\AvBitlyBundle\AvBitlyBundle::class => ['all' => true],
];
Configure the Bundle
Add the required parameters to config/packages/av_bitly.yaml (or config.yml in older Symfony versions):
av_bitly:
bitly_token: '%env(BITLY_TOKEN)%' # Replace with your Bitly API token
bitly_api_address: 'https://api-ssl.bitly.com' # Optional, default provided
bitly_domain: 'yourdomain' # Optional, default empty
First Use Case: Shortening a URL
Inject the bitly_service into your controller or service:
use AppVentus\AvBitlyBundle\Service\BitlyService;
class MyController extends AbstractController
{
public function shortenUrl(BitlyService $bitlyService)
{
$longUrl = 'https://example.com/very-long-url';
$shortUrl = $bitlyService->shorten($longUrl);
return new Response("Shortened URL: {$shortUrl}");
}
}
Service Injection
Always inject BitlyService via dependency injection (DI) to leverage Symfony’s container. Avoid instantiating the service manually.
URL Shortening
Use shorten() to generate a Bitly short URL:
$shortUrl = $bitlyService->shorten('https://example.com/long-path');
bitly_domain is configured).Error Handling
Wrap calls in a try-catch block to handle API failures gracefully:
try {
$shortUrl = $bitlyService->shorten($url);
} catch (\Exception $e) {
// Log or notify the user
$this->addFlash('error', 'Failed to shorten URL: ' . $e->getMessage());
}
Environment Variables
Store the bitly_token in .env for security:
BITLY_TOKEN=your_bitly_api_token_here
Reference it in config/packages/av_bitly.yaml as %env(BITLY_TOKEN)%.
Custom Domains
If using a custom Bitly domain (e.g., yourbrand.bit.ly), set bitly_domain in the config. The bundle will prepend this to shortened URLs automatically.
Batch Processing For bulk shortening, loop through URLs and process them sequentially (Bitly’s API may have rate limits):
$urls = ['url1', 'url2', 'url3'];
$shortUrls = [];
foreach ($urls as $url) {
$shortUrls[] = $bitlyService->shorten($url);
}
Caching Cache shortened URLs to avoid repeated API calls for the same input. Use Symfony’s cache system:
$cacheKey = 'bitly:' . md5($url);
$shortUrl = $cache->get($cacheKey);
if (!$shortUrl) {
$shortUrl = $bitlyService->shorten($url);
$cache->set($cacheKey, $shortUrl, 3600); // Cache for 1 hour
}
Token Validation
API Rate Limits
try {
$shortUrl = $bitlyService->shorten($url);
} catch (\Symfony\Component\HttpKernel\Exception\HttpException $e) {
if ($e->getStatusCode() === 429) {
sleep(2); // Wait before retrying
retry logic...
}
}
Domain Configuration
bitly_domain is set but the API returns a URL without it (e.g., bit.ly/abc123 instead of yourbrand.bit.ly/abc123), the bundle does not modify the returned URL. This is a Bitly API behavior, not a bundle bug.Deprecated Symfony Version
composer.json lists symfony/class-loader: 2.3.* as a dev dependency, suggesting it was built for Symfony 2.x. Use with caution in Symfony 4/5/6; test thoroughly for compatibility.No Additional Endpoints
shorten() method. For other Bitly API features (e.g., analytics, link management), you’ll need to:
Enable Debug Mode Symfony’s debug toolbar can help inspect HTTP requests/responses if the bundle makes them visible. If not, enable Guzzle middleware for logging:
// In a custom service or config
$client = new \GuzzleHttp\Client([
'handler' => \GuzzleHttp\HandlerStack::create([
new \GuzzleHttp\Middleware::tap(function ($request) {
error_log('Bitly Request: ' . $request->getUri());
}),
]),
]);
Check API Responses
If shorten() fails, inspect the raw response by extending the service:
class CustomBitlyService extends \AppVentus\AvBitlyBundle\Service\BitlyService
{
public function shorten($longUrl)
{
$response = $this->client->post($this->apiUrl, [
'json' => ['long_url' => $longUrl],
]);
error_log('Raw Response: ' . $response->getBody());
return parent::shorten($longUrl);
}
}
Token Permissions Ensure your Bitly token has the correct permissions (e.g., "Shorten links") in the Bitly API settings. Insufficient permissions will return HTTP 403.
Extension Points
Override the BitlyService to add custom logic:
// src/Service/CustomBitlyService.php
namespace App\Service;
use AppVentus\AvBitlyBundle\Service\BitlyService;
class CustomBitlyService extends BitlyService
{
public function shorten($longUrl)
{
// Pre-process $longUrl (e.g., append UTM parameters)
$processedUrl = $this->addUtmParams($longUrl);
return parent::shorten($processedUrl);
}
private function addUtmParams($url)
{
return $url . '?utm_source=your_app';
}
}
Register the custom service in config/services.yaml:
services:
App\Service\CustomBitlyService: ~
av_bitly.bitly_service: '@App\Service\CustomBitlyService'
Testing
Mock the BitlyService in PHPUnit tests:
$this->mockBuilder()
->disableOriginalConstructor()
->getMock()
->method('shorten')
->willReturn('http://bit.ly/test123');
Fallback for Offline Use Implement a fallback for when Bitly’s API is unavailable:
try {
$shortUrl = $bitlyService->shorten($url);
} catch (\Exception $e) {
$shortUrl = 'http://fallback.example.com/' . md5($url);
}
Logging Log shortened URLs for analytics or debugging:
$this->logger->info('Shortened URL', [
'original' => $url,
'shortened' => $shortUrl,
]);
How can I help you explore Laravel packages today?