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

Assets Referencer Bundle Laravel Package

betsol/assets-referencer-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to Begin

  1. Installation Run composer require betsol/assets-referencer-bundle ~1.0 in your Laravel project (note: this is a Symfony bundle, but can be adapted for Laravel via bridge packages like symfony/bundle or kris/laravel-symfony-bundle). If using Laravel directly, consider wrapping this in a custom service provider for compatibility.

  2. Configuration Add the bundle to your config/app.php under providers (if using a bridge) or manually register it in a custom provider:

    $this->register(new \Betsol\Bundle\AssetsReferencerBundle\AssetsReferencerBundle());
    

    Publish the config (if available) or define it in config/services.php:

    'assets_referencer' => [
        'base_url' => env('ASSETS_BASE_URL', 'http://static.example.com/'),
    ],
    
  3. First Use Case In a Twig template (or a Laravel Blade template via a custom directive), use the asset_reference function:

    <link rel="stylesheet" href="{{ asset_reference('css/app.css') }}">
    

    Ensure your template engine supports Twig functions (e.g., via twig/laravel or a custom bridge).


Implementation Patterns

Workflows

  1. Centralized Asset Management Use asset_reference for all static assets (CSS, JS, images) to enforce consistency. Example:

    {% for file in ['app.js', 'vendor.js', 'styles.css'] %}
        <script src="{{ asset_reference('js/' ~ file) }}"></script>
    {% endfor %}
    
  2. Dynamic Base URLs Override the base_url in config for different environments (e.g., dev, prod):

    // config/services.php
    'assets_referencer' => [
        'base_url' => env('APP_ENV') === 'prod'
            ? 'https://cdn.example.com'
            : 'http://localhost:8080/assets',
    ],
    
  3. Integration with Laravel Mix/Vite Combine with Laravel’s asset pipelines. Example:

    // vite.config.js
    export default {
        build: {
            outDir: 'public/assets', // Output to a subdirectory
        },
    };
    

    Then reference via:

    {{ asset_reference('assets/app.js') }}
    
  4. Twig in Laravel Blade Create a custom Blade directive to bridge Twig functions:

    // AppServiceProvider.php
    Blade::directive('asset', function ($path) {
        return "<?php echo app('assets_referencer')->reference(" . $path . "); ?>";
    });
    

    Usage:

    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    

Integration Tips

  • Caching: Leverage Laravel’s cache to store resolved asset paths if the bundle lacks built-in caching.
  • Asset Versioning: Append a query string for cache busting:
    {{ asset_reference('js/app.js?v=' ~ hash('md5', 'app.js')) }}
    
  • Environment-Specific Assets: Use conditional logic in Twig:
    {% if app.environment == 'dev' %}
        {{ asset_reference('js/dev.js') }}
    {% else %}
        {{ asset_reference('js/prod.js') }}
    {% endif %}
    

Gotchas and Tips

Pitfalls

  1. Symfony Dependency The bundle is Symfony-specific. For Laravel, you’ll need to:

    • Use a Symfony bridge (e.g., kris/laravel-symfony-bundle).
    • Manually wrap the bundle in a Laravel service provider.
    • Risk: Potential compatibility issues with Laravel’s asset handling (e.g., mix-manifest.json).
  2. Twig Requirement The bundle assumes Twig templates. For Blade-only projects:

    • Create a facade or helper to replicate the functionality.
    • Example:
      // app/Helpers/AssetHelper.php
      class AssetHelper {
          public static function reference($path) {
              return config('assets_referencer.base_url') . ltrim($path, '/');
          }
      }
      
      Usage in Blade:
      {{ AssetHelper::reference('css/app.css') }}
      
  3. Path Handling Quirks

    • The bundle does not automatically handle Laravel’s public folder. Prepend paths with / or configure base_url to include it:
      base_url: http://example.com/public/
      
    • Relative paths (e.g., ./images/logo.png) may break. Use absolute paths from the public root.
  4. Configuration Overrides The base_url config is global. To support multiple domains:

    • Extend the bundle or use middleware to dynamically set the base URL based on the request host.

Debugging

  • Broken Assets: Verify the base_url is correct and paths are absolute (e.g., css/app.css not ./css/app.css).
  • Twig Errors: Ensure the Twig environment is properly initialized (e.g., via twig/laravel or a custom provider).
  • Caching Issues: Clear Laravel’s cache (php artisan cache:clear) and Twig’s cache if applicable.

Extension Points

  1. Custom Functions Extend the bundle by adding more Twig functions (e.g., asset_versioned):

    // Extend the bundle's Twig loader
    $twig->addFunction(new \Twig\TwigFunction('asset_versioned', function ($path) {
        return asset_reference($path) . '?v=' . filemtime(public_path($path));
    }));
    
  2. Asset Processing Hook into the path resolution to add logic (e.g., minification checks):

    // Override the bundle's resolver
    $resolver = $bundle->getResolver();
    $resolver->addFilter(function ($path) {
        return str_replace('.css', '.min.css', $path);
    });
    
  3. Laravel Service Provider Bridge Create a Laravel-specific provider to abstract Symfony dependencies:

    // AppServiceProvider.php
    public function register() {
        $this->app->singleton('assets_referencer', function () {
            $container = new \Symfony\Component\DependencyInjection\Container();
            $container->set('assets_referencer.base_url', config('assets_referencer.base_url'));
            return new \Betsol\Bundle\AssetsReferencerBundle\AssetsReferencer($container);
        });
    }
    
  4. Testing Mock the asset_reference function in PHPUnit:

    Twig::createNumberFunction()->expects($this)->once()->with('css/app.css')->willReturn('http://static.example.com/css/app.css');
    
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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