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

Avbitly Bundle Laravel Package

appventus/avbitly-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. 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],
    ];
    
  2. 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
    
  3. 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}");
        }
    }
    

Implementation Patterns

Core Workflow

  1. Service Injection Always inject BitlyService via dependency injection (DI) to leverage Symfony’s container. Avoid instantiating the service manually.

  2. URL Shortening Use shorten() to generate a Bitly short URL:

    $shortUrl = $bitlyService->shorten('https://example.com/long-path');
    
    • Supports both absolute URLs and relative paths (if bitly_domain is configured).
  3. 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());
    }
    

Integration Tips

  • 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
    }
    

Gotchas and Tips

Pitfalls

  1. Token Validation

    • The bundle does not validate the Bitly token on configuration load. If the token is invalid, the first API call will fail silently or return an error. Test the token separately before relying on the bundle.
  2. API Rate Limits

    • Bitly’s API has rate limits (e.g., 500 requests/hour for free tier). Exceeding these will return HTTP 429 errors. Implement retry logic or exponential backoff:
      try {
          $shortUrl = $bitlyService->shorten($url);
      } catch (\Symfony\Component\HttpKernel\Exception\HttpException $e) {
          if ($e->getStatusCode() === 429) {
              sleep(2); // Wait before retrying
              retry logic...
          }
      }
      
  3. Domain Configuration

    • If 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.
  4. Deprecated Symfony Version

    • The bundle’s 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.
  5. No Additional Endpoints

    • The bundle only exposes the shorten() method. For other Bitly API features (e.g., analytics, link management), you’ll need to:
      • Use the raw Bitly API directly (via Guzzle or Symfony’s HTTP client).
      • Extend the bundle (see Extension Points below).

Debugging

  1. 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());
            }),
        ]),
    ]);
    
  2. 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);
        }
    }
    
  3. 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.


Tips

  1. 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'
    
  2. Testing Mock the BitlyService in PHPUnit tests:

    $this->mockBuilder()
        ->disableOriginalConstructor()
        ->getMock()
        ->method('shorten')
        ->willReturn('http://bit.ly/test123');
    
  3. 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);
    }
    
  4. Logging Log shortened URLs for analytics or debugging:

    $this->logger->info('Shortened URL', [
        'original' => $url,
        'shortened' => $shortUrl,
    ]);
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware