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

Bitly Bundle Laravel Package

botjaeger/bitly-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require botjaeger/bitly-bundle
    

    Add to config/bundles.php (Symfony 4+ auto-discovers, but explicit inclusion ensures compatibility):

    return [
        // ...
        Botjaeger\BitlyBundle\BitlyBundle::class => ['all' => true],
    ];
    
  2. Configuration Define Bitly API credentials in config/packages/bitly.yaml:

    bitly:
        client_id: '%env(BITLY_CLIENT_ID)%'
        client_secret: '%env(BITLY_CLIENT_SECRET)%'
        access_token: '%env(BITLY_ACCESS_TOKEN)%'
        api_version: 'v4'  # Default; verify with Bitly's latest API
    
  3. First Use Case Shorten a URL via a controller:

    use Botjaeger\BitlyBundle\Service\BitlyService;
    
    class UrlController extends AbstractController {
        public function shorten(UrlShortenerRequest $request, BitlyService $bitly): JsonResponse {
            $shortUrl = $bitly->shorten($request->get('longUrl'));
            return $this->json(['short_url' => $shortUrl]);
        }
    }
    

Implementation Patterns

Core Workflows

  1. URL Shortening

    // Basic shortening
    $bitly->shorten('https://example.com/very-long-url');
    
    // Custom domain (if configured)
    $bitly->shorten('https://example.com/long-url', ['domain' => 'mybrand.bit.ly']);
    
  2. URL Expansion

    $originalUrl = $bitly->expand('bit.ly/2XyZ123');
    
  3. Batch Operations

    $bitly->shortenBatch([
        'https://example.com/url1',
        'https://example.com/url2',
    ]);
    

Integration Tips

  • Dependency Injection Prefer injecting BitlyService over instantiating the client directly for consistency with bundle features (logging/profiling).

  • Configuration Overrides Extend default config via config/packages/bitly.yaml:

    bitly:
        options:
            timeout: 10  # Override default timeout
            retries: 3   # Add retry logic
    
  • Event Listeners Hook into Bitly events (e.g., bitly.shorten.success) via Symfony’s event dispatcher:

    # config/services.yaml
    services:
        App\EventListener\BitlyLogger:
            tags:
                - { name: 'kernel.event_listener', event: 'bitly.shorten.success', method: 'onShortenSuccess' }
    

Gotchas and Tips

Pitfalls

  1. Deprecated Bundle

    • The package is archived (no active maintenance). Validate compatibility with:
      • Symfony 5/6 (may require manual adjustments).
      • hpatoio/bitly-api (check for breaking changes in the underlying client).
  2. Token Management

    • Access tokens expire. Implement token refresh logic or use Bitly’s OAuth flow:
      $bitly->setAccessToken($newToken); // Manual refresh
      
  3. Rate Limiting

    • Bitly enforces rate limits. Handle 429 responses:
      try {
          $bitly->shorten($url);
      } catch (\RuntimeException $e) {
          if ($e->getCode() === 429) {
              // Retry or queue the request
          }
      }
      

Debugging

  • Enable Debug Mode Add to config/packages/bitly.yaml:

    bitly:
        debug: '%kernel.debug%'  # Logs requests/responses
    

    Check Symfony’s profiler (/_profiler) for Bitly API calls.

  • Common Errors

    Error Cause Fix
    InvalidClientId Wrong client_id/client_secret Verify .env values
    InvalidAccessToken Expired token Refresh token or regenerate
    InvalidUrl Malformed input URL Validate with filter_var($url, FILTER_VALIDATE_URL)
    DomainNotConfigured Custom domain not whitelisted in Bitly Use default domain or request access

Extension Points

  1. Custom Responses Override the default response handler:

    $bitly->setResponseHandler(function ($response) {
        return json_decode($response->getBody(), true);
    });
    
  2. Middleware Add request/response middleware:

    $bitly->getClient()->getEmitter()->attach(
        new \GuzzleHttp\Middleware::tap(function ($request) {
            $request = $request->withHeader('X-Custom-Header', 'value');
            return $request;
        })
    );
    
  3. Logging Extend the built-in logger to track custom metrics:

    $bitly->setLogger(new \Monolog\Logger('bitly_custom'));
    
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