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

adspray/short-url-bundle

Symfony bundle providing a URL shortener service and Twig filter. Generate short paths like /~ShE from long URLs in controllers or templates, and resolve short codes back to the original URL via routing and a simple shortener service.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    • Add the bundle via vendors install or Git submodule as per README.
    • Register the Bumz\ShortUrlBundle\BumzShortUrlBundle in AppKernel.php.
    • Include the routing in app/config/routing.yml:
      BumzShortUrlBundle:
          resource: "@BumzShortUrlBundle/Resources/config/routing.yml"
          prefix: /
      
  2. First Use Case:

    • Generate a short URL for a route (e.g., app_dev.php/users/show/123your.host/~users123).
    • Inject the short_url_generator service in a controller:
      use Bumz\ShortUrlBundle\Service\ShortUrlGenerator;
      
      class UsersController extends Controller {
          public function showAction($id) {
              $generator = $this->get('short_url_generator');
              $shortUrl = $generator->generate('users_show', ['id' => $id]);
              // Returns: "your.host/~users123"
          }
      }
      
  3. Twig Integration:

    • Use the short_url Twig filter in templates:
      <a href="{{ path('users_show', {'id': 123})|short_url }}">Short Link</a>
      

Implementation Patterns

Core Workflows

  1. Route-Based Shortening:

    • Generate short URLs for named routes (e.g., users_show~users{id}).
    • Example:
      $generator->generate('product_detail', ['slug' => 'laptop']);
      // Output: "your.host/~productlaptop"
      
  2. Dynamic Shortening:

    • Combine route names with dynamic parameters (e.g., blog_post + id=42~blog42).
    • Useful for SEO-friendly URLs or reducing link clutter.
  3. Twig Filters:

    • Apply the short_url filter to any route path:
      {{ path('homepage')|short_url }}  {# "your.host/~home" #}
      
  4. Custom Shortening Logic:

    • Extend the ShortUrlGenerator service to add custom rules (e.g., exclude certain routes):
      $generator->setExcludedRoutes(['admin_dashboard']);
      

Integration Tips

  • Symfony Forms: Use the Twig filter in form themes to shorten action URLs:
    <form action="{{ path('user_edit', {'id': user.id})|short_url }}">
    
  • API Responses: Return short URLs in JSON responses for mobile apps:
    return $this->json(['short_url' => $generator->generate('api_download', ['id' => 1])]);
    
  • Caching: Cache generated short URLs in a service layer to avoid regenerating them:
    $cache = $this->get('cache');
    $shortUrl = $cache->get('short_url_' . $routeName) ?: $generator->generate($routeName);
    

Gotchas and Tips

Pitfalls

  1. Route Name Collisions:

    • If two routes share the same name (e.g., home and homepage), the generator will produce ambiguous short URLs.
    • Fix: Use unique route names or override the generator’s logic.
  2. Parameter Sanitization:

    • The bundle doesn’t sanitize parameters by default (e.g., id=1&action=delete~users1actiondelete).
    • Fix: Pre-process parameters or extend the service to sanitize:
      $generator->setParameterSanitizer(function($params) {
          return array_map('urlencode', $params);
      });
      
  3. Routing Conflicts:

    • The ~ prefix might conflict with existing routes (e.g., your.host/~admin).
    • Fix: Configure a custom prefix in routing.yml or adjust the bundle’s routing logic.
  4. Case Sensitivity:

    • Short URLs are case-sensitive (e.g., ~UserShow~usershow).
    • Fix: Normalize route names to lowercase in the generator.

Debugging

  • 404 Errors: If a short URL returns a 404, verify:

    • The route exists in Symfony’s router.
    • The ~ prefix is correctly mapped in the bundle’s routing file.
    • No typos in route names or parameters.
  • Logging: Enable debug mode to trace short URL generation:

    $generator->setDebug(true); // Logs generated URLs to Symfony’s logger.
    

Extension Points

  1. Custom Short URL Format: Override the ShortUrlGenerator to change the format (e.g., your.host/s/{hash}):

    class CustomShortUrlGenerator extends \Bumz\ShortUrlBundle\Service\ShortUrlGenerator {
        protected function generateShortCode($routeName, $params) {
            return 's/' . md5($routeName . serialize($params));
        }
    }
    

    Register it as a service in services.yml:

    services:
        short_url_generator:
            class: AppBundle\Service\CustomShortUrlGenerator
            arguments: [...]
    
  2. Database Backing: Extend the bundle to store short URLs in a database for persistence:

    $generator->setStorage(new DoctrineShortUrlStorage($entityManager));
    
  3. Analytics: Add tracking to short URLs by wrapping the generator:

    $generator->setUrlWrapper(function($shortUrl) {
        return $shortUrl . '?utm_source=short_url';
    });
    

Configuration Quirks

  • Prefix Customization: The ~ prefix is hardcoded in the routing file. To change it:

    1. Override the bundle’s Resources/config/routing.yml in your project.
    2. Update the _path pattern (e.g., /{shortCode}/s/{shortCode}).
  • Parameter Handling: The bundle concatenates parameters directly. For complex cases (e.g., arrays), implement a custom ShortUrlGenerator:

    protected function generateShortCode($routeName, $params) {
        return $routeName . '_' . md5(serialize($params));
    }
    
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.
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
anil/file-picker
broqit/fields-ai