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

Short Url Bundle Laravel Package

alanmastro/short-url-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install via Composer (preferred method):

    composer require alanmastro/short-url-bundle
    

    (Note: The original README uses Git submodule, but Composer is cleaner for modern Laravel/Symfony integration.)

  2. Register the Bundle (if using Symfony/Symfony-like structure): Add to config/bundles.php:

    return [
        // ...
        Bumz\ShortUrlBundle\BumzShortUrlBundle::class => ['all' => true],
    ];
    
  3. Publish Config (if needed):

    php artisan vendor:publish --tag=bumz-short-url-config
    

    (Check config/short_url.php for customization like base path, hash length, or storage.)

  4. First Use Case: Generate a short URL in a controller:

    $shortUrl = app('bumz_short_url.shortener')->shorten('https://example.com/long-url');
    // Returns: "/~abc123" (or your configured prefix)
    

Implementation Patterns

Core Workflows

  1. Shortening URLs:

    • Controller:
      $shortener = app('bumz_short_url.shortener');
      $shortUrl = $shortener->shorten('https://example.com');
      
    • Twig Template:
      <a href="{{ 'https://example.com' | shortenUrl }}">Short Link</a>
      
    • API Response:
      return response()->json(['short_url' => $shortUrl]);
      
  2. Resolving Short URLs:

    • Reverse-lookup in controllers/APIs:
      $longUrl = app('bumz_short_url.shortener')->getLong('abc123');
      
    • Route-based resolution (handled automatically via routing.yml).
  3. Custom Short Codes:

    • Pre-generate a short code (e.g., for marketing):
      $shortCode = app('bumz_short_url.shortener')->generateShortCode();
      $shortener->storeShortUrl($shortCode, 'https://example.com');
      

Integration Tips

  • Laravel-Specific: Use the service container directly:

    $shortener = resolve('bumz_short_url.shortener');
    

    Or bind it in AppServiceProvider:

    $this->app->bind('shortener', function() {
        return app('bumz_short_url.shortener');
    });
    
  • Middleware for Short URLs: Protect short URLs with middleware (e.g., rate-limiting):

    Route::get('/~{short}', [ShortUrlController::class, 'redirect'])
         ->middleware('throttle:10,1');
    
  • Storage Backend: Extend the default storage (e.g., switch to Redis):

    $shortener->setStorage(new RedisShortUrlStorage());
    
  • Custom Hashing: Override the default hash generator (e.g., for alphanumeric-only):

    $shortener->setHashGenerator(new CustomHashGenerator());
    

Gotchas and Tips

Pitfalls

  1. Route Conflicts:

    • The bundle assumes a /~{short} route. Ensure no other routes conflict (e.g., Laravel’s default routes).
    • Fix: Adjust the prefix in routing.yml or use a custom route name.
  2. Case Sensitivity:

    • Short codes are case-sensitive by default (e.g., ABCabc).
    • Fix: Normalize case in ShortUrlStorage:
      $shortCode = strtolower($shortCode);
      
  3. Collision Risk:

    • Default hash length (e.g., 6 chars) may cause collisions for high traffic.
    • Fix: Increase length in config or use a stronger hash algorithm.
  4. Caching:

    • The bundle doesn’t cache resolved URLs by default. For high traffic, add a cache layer:
      $longUrl = Cache::remember("short_{$shortCode}", 3600, function() use ($shortCode) {
          return app('bumz_short_url.shortener')->getLong($shortCode);
      });
      
  5. Laravel-Symfony Mismatch:

    • The bundle is Symfony-centric. In Laravel, avoid get() in favor of app() or dependency injection.
    • Fix: Use Laravel’s service container:
      $shortener = app('bumz_short_url.shortener');
      

Debugging Tips

  • Check Storage: Dump the storage backend to verify entries:

    dd(app('bumz_short_url.shortener')->getStorage()->all());
    
  • Log Short Codes: Add logging for debugging collisions:

    $shortener->setLogger(new SingleUseLogHandler(
        Storage::disk('logs')->path('short_url.log')
    ));
    
  • Test Routes: Manually test short URLs:

    curl http://your.app/~abc123
    

    (Should return a 301/302 redirect to the long URL.)

Extension Points

  1. Custom Storage: Implement Bumz\ShortUrlBundle\Storage\ShortUrlStorageInterface:

    class DatabaseShortUrlStorage implements ShortUrlStorageInterface {
        // ...
    }
    

    Register it in services.yml:

    bumz_short_url.shortener.storage: '@database_short_url_storage'
    
  2. Custom Hash Generator: Extend Bumz\ShortUrlBundle\Generator\ShortUrlGenerator:

    class Base62Generator extends ShortUrlGenerator {
        protected function generateHash() { /* ... */ }
    }
    
  3. Event Listeners: Listen for short.url.created or short.url.resolved events to log/analyze usage.

  4. Laravel Blade Directives: Add a Blade directive for short URLs:

    Blade::directive('short', function($url) {
        return "<?php echo app('bumz_short_url.shortener')->shorten($url); ?>";
    });
    

    Usage:

    <a href="@short('https://example.com')">Link</a>
    
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope