Asset Utilities

Lightpack’s Asset utility provides a feature rich toolkit for managing, versioning, and rendering static assets (CSS, JS, images, fonts) in your PHP applications. It supports cache-busting, CDN integration, HTML tag generation, and Google Font management—all with a clear, expressive API and robust test coverage.


Overview


Common Challenges

Lightpack's asset loading facility tries to solve some of the most common challenges for which developers usually prefer frontend build tools usually in Node.js.

1. Basic Asset Loading

Problem: Managing and loading different types of assets

Pain Points:

2. Cache Busting

Problem: Browser caching of outdated assets

Pain Points:

3. Development vs Production

Problem: Different needs for different environments

Pain Points:

4. Asset Organization

Problem: Managing multiple assets efficiently

Pain Points:

5. Module Dependencies

Problem: Managing JavaScript module dependencies

Pain Points:

6. Performance

Problem: Optimizing asset delivery

Pain Points:

Read further to gain an understanding of how Asset utility solves above challenges and reduces the need to depend on external build tools.

Asset URL Generation & Versioning

use Lightpack\Utils\Asset;

$asset = new Asset(); // Defaults to assets in public directory

// Asset url for public/css/app.css file
$url = $asset->url('css/app.css'); 

Disable versioning if needed:

$url = $asset->url('css/app.css', false); // /css/app.css

CDN Support:

$asset->url('css/app.css'); // https://cdn.example.com/css/app.css?v=...

HTML Helpers

CSS & JS

// Render CSS and JS tags
$html = $asset->load(['css/app.css', 'js/app.js']);
// <link rel='stylesheet' ...><script src='...' defer></script>

JS files use defer attribute by default; pass async or null for other modes. Choose one based on the script's purpose:

If neither defer nor async is used, the script is treated as "render-blocking" which means:

This is useful when you have scripts that:

Images

// Render an <img> tag with attributes
$html = $asset->img('img/logo.png', ['alt' => 'Logo', 'width' => 200]);
// <img src='/img/logo.png?v=...' alt='Logo' width='200'>

ES Modules

// Render <script type="module"> for JS modules
$html = $asset->module('js/app.js');
$html = $asset->module(['js/app.js' => null, 'js/utils.js' => 'async']);

Import Maps

// Generate an import map for ES modules
$html = $asset->importMap([
    'uikit' => 'js/uikit.js',
    'app' => 'js/app.js',
]);
// <script type='importmap'>...</script>

Google Fonts Downloader

// Download and locally host a Google Font
$asset->googleFont('Roboto', [400, 700]);
// Downloads font files, generates local CSS, and updates manifest

Version Manifest Management

$asset->generateVersions();

Asset Management Best Practices