assetflow/asset-flow
Composer 安装命令:
composer require assetflow/asset-flow
包简介
A comprehensive CodeIgniter 4 library for managing UI framework assets with support for multiple adapters, caching, minification, and theming.
关键字:
README 文档
README
AssetFlow is a comprehensive CodeIgniter 4 library for managing UI framework assets with support for multiple adapters, caching, minification, theming, and advanced production optimization features. It provides a clean, extensible architecture that allows developers to easily switch between different UI frameworks while maintaining consistent asset management practices across their applications. The library has evolved beyond basic asset management to become a complete front-end optimization solution, incorporating modern web performance techniques such as asset bundling, cache busting, image optimization, critical CSS extraction, and content security policy management.
This library was created to solve a common problem in CodeIgniter development: managing multiple UI frameworks and their associated assets across different projects. Instead of manually including CSS and JavaScript files for each framework, AssetFlow provides a unified interface that handles asset registration, CDN fallback, caching, and theming automatically. The adapter pattern makes it simple to switch between frameworks or add support for new ones without modifying the core library code. The advanced features introduced in recent updates extend this capability to production-ready deployments, enabling developers to achieve excellent Core Web Vitals scores and meet modern web performance standards.
AssetFlow supports eight UI framework adapters out of the box, including popular choices like Bootstrap 5 and Tailwind CSS, as well as creative adapters for special use cases like retro gaming interfaces, glassmorphism designs, and cyberpunk aesthetics. The new ComponentBridge adapter enables seamless integration of Vue.js and React components within CodeIgniter views, bridging the gap between server-side and client-side rendering paradigms. Each adapter implements a consistent interface, ensuring that switching between frameworks requires only a single configuration change rather than extensive code modifications.
AssetFlow was authored by Kazashim Kuzasuwat, a software developer passionate about creating clean, maintainable code solutions for common web development challenges. For questions, suggestions, or contributions, please contact the author at kazashimkuzasuwat@gmail.com.
1. Installation
1.1 Prerequisites
Before installing AssetFlow, ensure your development environment meets the following requirements. CodeIgniter 4.0 or higher is required, as the library leverages modern features of the framework including the configuration system, service containers, and cache handlers. PHP 8.0 or higher is recommended for optimal performance, though the library maintains compatibility with PHP 7.4 for projects that have not yet upgraded. For the advanced image optimization features, the GD extension or ImageMagick must be available on the server. For production deployments using asset bundling, ensure the project has write access to the public/assets directory for generated bundle files.
Your project should have Composer installed for dependency management, as AssetFlow follows modern PHP packaging practices. If you are working within an existing CodeIgniter 4 project, AssetFlow can be integrated seamlessly without requiring changes to your application's structure. For new projects, you may start with a fresh CodeIgniter 4 installation and add AssetFlow as described below. The library is designed to work alongside existing CodeIgniter asset management approaches, allowing gradual migration without disrupting current implementations.
The library includes optional dependencies for enhanced functionality. The matthiasmullie/minify package provides advanced JavaScript minification when the basic built-in minifier does not meet your requirements. For caching, AssetFlow supports multiple backends including Redis and Memcached when the corresponding PHP extensions are available. The file-based caching driver works without additional dependencies and is suitable for most use cases. The advanced features utilize additional optional dependencies that are automatically installed when using Composer to require the package with its suggested dependencies.
1.2 Installing via Composer
The recommended method for installing AssetFlow is through Composer, which handles autoloading and dependency management automatically. Open your terminal or command prompt, navigate to your CodeIgniter 4 project directory, and execute the following command to add AssetFlow to your project's dependencies. This command will download the latest stable version along with all required dependencies.
The AssetFlow library is available through Packagist under the assetflow/asset-flow package name. Add the package to your project using the Composer require command, which will automatically update your composer.json file and download all necessary files. Composer will also configure the autoloader to make AssetFlow classes available throughout your application.
composer require assetflow/asset-flow
If you want to include the optional dependencies for enhanced minification and image optimization capabilities, install the package with its suggested dependencies. This provides access to advanced features that may require additional external libraries for optimal performance.
composer require assetflow/asset-flow --with-dependencies
For projects that require the latest development version or need to test specific features not yet released, you can install directly from the GitHub repository by adding a VCS repository reference to your composer.json configuration.
{
"repositories": [
{
"type": "vcs",
"url": "https://github.com/kazashim/assetflow"
}
],
"require": {
"assetflow/asset-flow": "dev-main as 1.0.0"
}
}
After adding the repository configuration, run composer update to download and install the package along with its dependencies. Composer will automatically generate the autoloader configuration and make the AssetFlow classes available throughout your application. Run composer dump-autoload if you encounter any autoloading issues after installation.
1.3 Manual Installation
For projects that do not use Composer or for situations where you need to integrate AssetFlow without modifying your dependency configuration, manual installation is possible. Download the latest release from the GitHub repository releases page, then extract the archive to a temporary directory. Review the release notes to understand what features are included in that version and ensure compatibility with your project requirements.
Copy the app/Libraries/AssetFlow directory to your CodeIgniter application's app/Libraries/ directory. This directory contains all the core library files, adapter implementations, and driver classes needed for operation. If your application uses a different namespace for application classes, you may need to update the namespace declarations in the library files to match your configuration. Copy the app/Config/AssetFlow.php file to your application's app/Config/ directory, adjusting any configuration values as needed for your environment. The configuration file controls all runtime behavior including which adapter is used, caching settings, and advanced feature configurations.
For manual installation, you must ensure that the library files are properly autoloaded by CodeIgniter's autoloader. Add the following to your app/Config/Autoload.php file in the $classmap array if you encounter any autoloading issues. This maps the fully qualified class names to their file locations, ensuring PHP can locate and load the classes correctly.
$classmap = [ 'App\\Libraries\\AssetFlow\\AssetManager' => APPPATH . 'Libraries/AssetFlow/AssetManager.php', 'App\\Libraries\\AssetFlow\\Drivers\\Minifier' => APPPATH . 'Libraries/AssetFlow/Drivers/Minifier.php', 'App\\Libraries\\AssetFlow\\Drivers\\Cacher' => APPPATH . 'Libraries/AssetFlow/Drivers/Cacher.php', 'App\\Libraries\\AssetFlow\\Drivers\\AssetBundler' => APPPATH . 'Libraries/AssetFlow/Drivers/AssetBundler.php', 'App\\Libraries\\AssetFlow\\Drivers\\ImageOptimizer' => APPPATH . 'Libraries/AssetFlow/Drivers/ImageOptimizer.php', 'App\\Libraries\\AssetFlow\\Drivers\\CriticalCssLoader' => APPPATH . 'Libraries/AssetFlow/Drivers/CriticalCssLoader.php', 'App\\Libraries\\AssetFlow\\Drivers\\SecurityHeaders' => APPPATH . 'Libraries/AssetFlow/Drivers/SecurityHeaders.php', // Add adapter class mappings as needed ];
1.4 Directory Structure
After successful installation, your project structure should include the AssetFlow library files in the expected locations. The library is organized into logical components that separate concerns and make the codebase maintainable. Understanding this structure will help you navigate the library files when customizing adapters, extending functionality, or troubleshooting issues. The advanced features introduced in recent versions add new driver classes to support asset bundling, image optimization, critical CSS extraction, and security header management.
The main library directory contains the AssetManager class, which serves as the primary entry point for all library operations. This class coordinates the adapter system, caching, minification, and asset rendering. The Interfaces directory contains the UiAdapterInterface that all adapters must implement, ensuring consistency across different framework integrations. The Adapters directory contains the concrete implementations for each supported UI framework, including both popular frameworks and creative adapters for specialized use cases.
The Drivers directory houses supporting functionality including the Minifier class for CSS and JavaScript compression, the Cacher class for managing cached asset output, and the new advanced feature drivers. The AssetBundler class manages the concatenation and optimization of multiple assets into efficient bundles. The ImageOptimizer class handles on-the-fly image conversion, resizing, and format optimization including WebP conversion. The CriticalCssLoader class extracts and inlines critical CSS for improved first contentful paint performance. The SecurityHeaders class generates and manages content security policy headers for enhanced application security.
your-project/
├── app/
│ ├── Config/
│ │ └── AssetFlow.php # Library configuration
│ └── Libraries/
│ └── AssetFlow/
│ ├── AssetManager.php # Main library class
│ ├── Interfaces/
│ │ └── UiAdapterInterface.php
│ ├── Drivers/
│ │ ├── Minifier.php
│ │ ├── Cacher.php
│ │ ├── AssetBundler.php # Advanced: Asset bundling
│ │ ├── ImageOptimizer.php # Advanced: Image optimization
│ │ ├── CriticalCssLoader.php # Advanced: Critical CSS
│ │ └── SecurityHeaders.php # Advanced: CSP management
│ └── Adapters/
│ ├── Bootstrap5.php
│ ├── Tailwind.php
│ ├── Bulma.php
│ ├── Materialize.php
│ ├── RetroNES.php
│ ├── GlassUi.php
│ ├── CyberPunk.php
│ └── ComponentBridge.php # Advanced: Vue/React integration
└── public/
└── assets/
└── vendor/ # Local asset storage
2. Configuration
2.1 Basic Configuration
The AssetFlow library is configured through the App\Config\AssetFlow configuration file, which provides sensible defaults while allowing customization for specific project requirements. After installation, copy the provided configuration file to your application's config directory if it was not automatically placed there during the installation process. The configuration file uses CodeIgniter's BaseConfig class, which provides validation and type casting for configuration values. You can modify the configuration by editing the property values directly or by setting configuration values in your controller or bootstrap files for environment-specific overrides.
The configuration file is organized into logical sections covering core settings, adapter configuration, caching behavior, and advanced feature options. The following example demonstrates a comprehensive configuration setup for a production environment that uses CDN resources with aggressive caching, asset bundling, and security features enabled. Review each configuration section to understand the available options and their effects on library behavior.
<?php namespace App\Config; use CodeIgniter\Config\BaseConfig; class AssetFlow extends BaseConfig { // Default UI framework adapter public $defaultAdapter = 'bootstrap5'; // Environment: 'development' or 'production' public $environment = 'production'; // Use CDN URLs for framework assets public $preferCdn = true; // Fall back to local assets if CDN fails public $cdnFallback = true; // Enable asset caching public $cacheEnabled = true; // Cache TTL in seconds (86400 = 24 hours) public $cacheTtl = 86400; // Minify CSS assets public $minifyCss = true; // Minify JavaScript assets public $minifyJs = true; // Enable asset bundling for production public $bundleAssets = true; // Enable cache busting with content hashes public $cacheBusting = true; // Enable image optimization public $imageOptimization = true; // Enable critical CSS extraction public $criticalCssEnabled = true; // Enable security headers (CSP) public $securityHeadersEnabled = true; // Default theme configuration public $theme = [ 'primary' => '#6366f1', 'secondary' => '#8b5cf6', ]; }
2.2 Advanced Feature Configuration
The advanced features introduced in recent versions require additional configuration to operate correctly. Asset bundling combines multiple CSS and JavaScript files into single optimized bundles, reducing HTTP requests and improving page load times. Image optimization enables automatic WebP conversion, lazy loading, and responsive image generation. Critical CSS extraction identifies and inlines styles needed for above-the-fold content, improving first contentful paint metrics. Security headers generate content security policy directives to protect against cross-site scripting attacks and other common vulnerabilities.
The following configuration example demonstrates the advanced feature settings in detail. These settings enable production-ready optimizations while maintaining development flexibility. Each feature can be independently enabled or disabled based on project requirements and server capabilities. The bundling configuration defines bundle groups that combine related assets together, while the image optimization settings control format conversion and quality parameters.
<?php namespace App\Config; use CodeIgniter\Config\BaseConfig; class AssetFlow extends BaseConfig { // Core settings public $defaultAdapter = 'bootstrap5'; public $environment = 'production'; // Asset bundling configuration public $bundleAssets = true; public $bundles = [ 'css' => [ 'framework' => ['bootstrap', 'custom'], 'vendor' => ['font-awesome'], 'app' => ['main', 'components'], ], 'js' => [ 'framework' => ['bootstrap'], 'vendor' => ['jquery', 'font-awesome'], 'app' => ['main', 'components'], ], ]; // Cache busting settings public $cacheBusting = true; public $cacheBustingStrategy = 'content_hash'; // content_hash, query_string, or filename // Image optimization configuration public $imageOptimization = true; public $imageOptimizationConfig = [ 'convert_to_webp' => true, 'webp_quality' => 85, 'lazy_loading' => true, 'responsive_breakpoints' => [480, 768, 1024, 1280, 1920], 'default_width' => null, 'default_height' => null, 'fit_mode' => 'cover', // cover, contain, fill, inside, outside 'output_directory' => 'public/assets/optimized', ]; // Critical CSS configuration public $criticalCssEnabled = true; public $criticalCssConfig = [ 'inline_limit' => 10240, // 10KB inline limit 'extract_above_fold' => true, 'strategy' => 'size', // size, viewport, or hybrid 'output_path' => 'public/assets/critical', ]; // Security headers configuration public $securityHeadersEnabled = true; public $securityHeadersConfig = [ 'csp_enabled' => true, 'csp_report_only' => false, 'csp_directives' => [ 'default-src' => ["'self'"], 'script-src' => ["'self'", "'unsafe-inline'", 'cdn.example.com'], 'style-src' => ["'self'", "'unsafe-inline'"], 'img-src' => ["'self'", 'data:', 'blob:'], 'font-src' => ["'self'", 'fonts.googleapis.com', 'fonts.gstatic.com'], ], 'generate_nonce' => true, 'hsts_enabled' => true, 'hsts_max_age' => 31536000, 'x_frame_options' => 'SAMEORIGIN', 'x_content_type_options' => 'nosniff', ]; // Theme configuration public $theme = [ 'primary' => '#6366f1', 'secondary' => '#8b5cf6', ]; }
2.3 Adapter Configuration
The defaultAdapter setting determines which UI framework is loaded when the AssetManager is instantiated without specifying an adapter explicitly. The available adapter names correspond to the adapter class names in lowercase: bootstrap5, tailwind, bulma, materialize, retrones, glassui, cyberpunk, and componentbridge. Choose the adapter that matches your project's primary UI framework to minimize additional configuration. You can override the default adapter at runtime by calling the setAdapter method on the AssetManager instance, which is useful when your application needs to render different pages with different UI frameworks.
$assets = new AssetManager(); $assets->setAdapter('tailwind');
The ComponentBridge adapter requires additional configuration to specify which JavaScript framework and components to load. This adapter enables the integration of Vue.js and React components within CodeIgniter views, providing a bridge between server-side rendering and client-side interactivity. Configure the component mappings and framework settings to establish the connection between your PHP views and JavaScript components.
$assets->setAdapter('componentbridge'); $assets->configureComponents([ 'framework' => 'vue', 'root_id' => 'app', 'components' => [ 'Header' => '/js/components/Header.vue', 'Footer' => '/js/components/Footer.vue', ], 'hydration' => true, ]);
2.4 Environment Configuration
The environment setting controls several behaviors that affect asset delivery and performance. In development mode, assets are served unminified and local file paths are preferred over CDN URLs, making debugging easier. Production mode enables minification, prefers CDN resources for better caching, and enables aggressive caching of compiled asset output. The environment setting also affects how advanced features operate, with production mode enabling all optimizations and development mode preserving readability for troubleshooting.
You can switch between environments programmatically by calling the enableDevelopment or enableProduction methods, which also clear any cached asset output to ensure the new environment settings take effect immediately. This allows dynamic environment switching based on configuration or route conditions without requiring separate configuration files for each environment.
$assets = new AssetManager(); // Enable development mode $assets->enableDevelopment(); // Enable production mode $assets->enableProduction(); // Check current environment $isProduction = $assets->isProduction();
2.5 CDN Configuration
The preferCdn setting determines whether CDN URLs or local file paths are used for framework assets. When enabled, AssetFlow generates link and script tags pointing to CDN providers like jsDelivr, cdnjs, or unpkg depending on the adapter's configuration. When disabled, AssetFlow expects framework assets to be available in the public/assets/vendor/{adapter}/ directory. The cdnFallback setting enables automatic fallback to local assets when CDN resources fail to load, which is particularly valuable for applications that must work offline or in environments with restricted internet access.
$config = [ 'preferCdn' => true, 'cdnFallback' => true, 'assetPathBase' => '/assets/vendor', ];
2.6 Caching Configuration
AssetFlow includes a sophisticated caching system that stores compiled HTML output to minimize processing overhead on subsequent requests. The cacheEnabled setting toggles this functionality, while cacheTtl controls how long cached content remains valid in seconds. The default TTL of 86400 provides a full day of caching for production deployments. The cacheDriver setting specifies which cache backend to use, with support for file-based caching, Redis, Memcached, and a dummy driver for testing.
public $cacheEnabled = true; public $cacheTtl = 86400; // 24 hours public $cacheDriver = 'file'; // file, redis, memcached, dummy public $cachePrefix = 'assetflow_';
2.7 Theme Configuration
The theme configuration array allows you to customize the appearance of your UI framework through CSS custom properties. Each adapter interprets theme variables differently, translating them into framework-specific CSS variables that override default styling. The theme configuration is passed to the adapter's getThemeVariables method, which generates the appropriate CSS. The library also includes preset theme configurations for common styling scenarios that can be applied using the setPreset method.
public $theme = [ 'primary' => '#6366f1', // Main brand color 'secondary' => '#8b5cf6', // Secondary color 'radius' => '0.5rem', // Border radius 'body-bg' => '#f8fafc', // Background color 'body-color' => '#1e293b', // Text color ]; // Apply preset themes $assets->setPreset('dark'); // Dark mode theme $assets->setPreset('corporate'); // Professional colors $assets->setPreset('startup'); // Modern tech aesthetic
3. Usage
3.1 Basic Usage
Using AssetFlow in your CodeIgniter application involves three main steps: initializing the AssetManager, configuring the adapter and theme, and rendering the asset tags in your views. The library is designed to be intuitive while providing powerful customization options for advanced use cases. Begin by creating an AssetManager instance in your controller, either using the default configuration or passing custom options to customize the behavior. The library is instantiated as a standard PHP object without requiring service container registration, making it easy to use in any part of your application.
<?php namespace App\Controllers; use App\Libraries\AssetFlow\AssetManager; class Welcome extends BaseController { public function index() { $assets = new AssetManager([ 'default_adapter' => 'bootstrap5', 'prefer_cdn' => true, 'theme' => [ 'primary' => '#4f46e5', 'secondary' => '#7c3aed', ], ]); return view('welcome_message', [ 'assets' => $assets, ]); } }
In your view file, render the asset tags in the appropriate locations. The renderHead method generates all CSS links, meta tags, preconnect hints, and theme CSS variables. The renderScripts method generates JavaScript tags and initialization scripts. The renderBodyAttributes method returns HTML attributes for the body element that may be required by certain frameworks. The renderSecurityHeaders method outputs the configured security headers if enabled, which should be called before any output is sent to the browser.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <?= $assets->renderSecurityHeaders() ?> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <?= $assets->renderHead() ?> </head> <body <?= $assets->renderBodyAttributes() ?>> <div class="container"> <h1>Welcome to AssetFlow</h1> <p>This page uses the AssetFlow library for asset management.</p> </div> <?= $assets->renderScripts() ?> </body> </html>
3.2 Advanced Configuration
For applications with complex asset management requirements, AssetFlow provides methods for dynamic configuration at runtime. You can chain multiple configuration calls to build the desired asset setup before rendering output. The setVersion method allows you to specify a particular version of the UI framework to use, overriding the adapter's default version. This is useful when you need to maintain compatibility with specific component versions or when upgrading framework versions gradually across a large application.
$assets = new AssetManager(); $assets->setAdapter('bootstrap5') ->setVersion('5.3.0') ->setTheme([ 'primary' => '#6366f1', 'radius' => '0.5rem', ]);
The addCss and addJs methods allow you to register additional CSS and JavaScript assets that are not part of the primary UI framework. This is useful for page-specific scripts, third-party plugins, or custom stylesheets that need to be included alongside the framework assets. You can specify additional attributes like media queries for CSS or defer/async loading for JavaScript.
$assets = new AssetManager(); // Add custom CSS $assets->addCss('/css/custom-styles.css', ['media' => 'screen']); $assets->addCss('/css/print-styles.css', ['media' => 'print']); // Add custom JavaScript $assets->addJs('/js/page-specific.js', ['defer' => true]); $assets->addJs('https://cdn.example.com/tracker.js', ['async' => true]);
3.3 Asset Bundling
Asset bundling combines multiple CSS and JavaScript files into single optimized bundles, reducing HTTP requests and improving page load times. The bundling system groups related assets together and generates bundled files that can be served efficiently. Bundling is particularly beneficial in production environments where multiple requests for small files can add significant latency. Enable bundling in the configuration and define bundle groups to organize your assets effectively.
// Configure bundling $assets = new AssetManager([ 'bundleAssets' => true, ]); // Define custom bundles $assets->defineBundle('css', 'main', [ '/css/reset.css', '/css/base.css', '/css/components.css', '/css/layout.css', ]); $assets->defineBundle('js', 'vendor', [ '/js/vendor/jquery.js', '/js/vendor/lodash.js', ]); $assets->defineBundle('js', 'app', [ '/js/app/main.js', '/js/app/components.js', '/js/app/utils.js', ]); // Register bundles for rendering $assets->registerBundle('css', 'main'); $assets->registerBundle('js', 'app'); // Render bundled assets echo $assets->renderHead(); // Includes bundled CSS echo $assets->renderScripts(); // Includes bundled JS
The bundling system supports multiple bundle groups for different sections of your application. You can create bundles for framework assets, vendor libraries, and application code separately, then load only the bundles needed for each page. This approach provides flexibility while maintaining the performance benefits of reduced HTTP requests.
// Define framework bundle $assets->defineBundle('css', 'framework', [ '/css/framework/bootstrap.css', '/css/framework/components.css', ]); // Define vendor bundle for third-party libraries $assets->defineBundle('js', 'vendor', [ '/js/vendor/react.production.min.js', '/js/vendor/react-dom.production.min.js', ]); // Define page-specific bundles $assets->defineBundle('js', 'dashboard', [ '/js/dashboard/charts.js', '/js/dashboard/tables.js', ]); // Load only needed bundles $assets->registerBundle('css', 'framework'); $assets->registerBundle('js', 'vendor'); $assets->registerBundle('js', 'dashboard');
3.4 Cache Busting
Cache busting ensures that browsers download updated assets when content changes, preventing users from seeing stale cached versions of your files. AssetFlow supports multiple cache busting strategies including content hash-based naming, query string versioning, and filename-based versioning. The content hash strategy appends a hash of the file contents to the filename, automatically invalidating the cache when files change. The query string strategy adds a version parameter to the URL, which is simpler to implement but less effective with some CDN configurations. The filename strategy embeds the version or hash directly in the filename, requiring file renaming but providing maximum compatibility.
$assets = new AssetManager([ 'cacheBusting' => true, 'cacheBustingStrategy' => 'content_hash', ]); // Get cache-busted URL for an asset $cssUrl = $assets->getCacheBustedUrl('/css/main.css'); // Returns: /css/main.a1b2c3d4.css
When using cache busting, configure your web server to serve files correctly when the filename contains the hash. Most web servers handle this automatically for static files, but you may need to configure URL rewriting for more complex scenarios. The following example shows how to configure Apache for filename-based cache busting.
<IfModule mod_rewrite.c> RewriteEngine On # Strip cache busting hash from filename RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.+)\.[a-f0-9]{8}\.(css|js)$ $1.$2 [L] </IfModule>
3.5 Image Optimization
AssetFlow includes comprehensive image optimization features that automatically convert images to WebP format, generate responsive image sets, and implement lazy loading. These optimizations significantly reduce page weight and improve load times, particularly on mobile devices with slower connections. The image optimization system integrates seamlessly with the asset management workflow, allowing you to process images through the same configuration and rendering methods used for CSS and JavaScript.
$assets = new AssetManager([ 'imageOptimization' => true, ]); // Configure image optimization $assets->configureImageOptimization([ 'convert_to_webp' => true, 'webp_quality' => 85, 'lazy_loading' => true, 'responsive_breakpoints' => [480, 768, 1024, 1280, 1920], ]); // Render an optimized image echo $assets->renderImage('/images/hero.jpg', [ 'alt' => 'Hero image', 'class' => 'img-fluid', 'width' => 1200, 'height' => 600, ]);
The renderImage method generates optimized HTML with appropriate srcset attributes for responsive images, lazy loading attributes, and automatic WebP fallbacks. The output includes multiple image sources at different breakpoints, allowing browsers to download the most appropriate size for the current viewport. The method also generates picture element markup when both WebP and original format sources are needed.
// Advanced image rendering with responsive sizes echo $assets->renderImage('/images/product.jpg', [ 'alt' => 'Product image', 'sizes' => '(max-width: 480px) 100vw, (max-width: 768px) 50vw, 33vw', 'class' => 'product-image', 'loading' => 'lazy', 'decoding' => 'async', 'figure' => true, 'figcaption' => 'Product description', ]);
For images within content areas or those added through other means, you can use the optimizeImage helper to process individual images. This method returns the path to the optimized image along with generated responsive variants.
// Optimize an image and get the results $result = $assets->optimizeImage('/uploads/photo.jpg', [ 'max_width' => 800, 'max_height' => 600, 'quality' => 80, ]); // Returns an array with original, webp, and responsive versions $webpPath = $result['webp']; $srcset = $result['srcset'];
3.6 Critical CSS
Critical CSS extraction identifies and inlines the styles needed to render above-the-fold content, improving first contentful paint metrics and perceived page load speed. The critical CSS loader analyzes your CSS and extracts the rules that apply to elements visible in the initial viewport, inlining them directly in the HTML head while deferring the remaining styles. This technique is particularly effective for improving Core Web Vitals scores and has been shown to significantly improve user experience metrics.
$assets = new AssetManager([ 'criticalCssEnabled' => true, ]); // Configure critical CSS extraction $assets->configureCriticalCss([ 'inline_limit' => 10240, // 10KB inline limit 'extract_above_fold' => true, 'strategy' => 'size', // size, viewport, or hybrid ]); // Render head with critical CSS inlined echo $assets->renderHead(); // Outputs: <style>/* Critical CSS inlined */</style> // <link rel="stylesheet" href="/css/main.css" media="print" onload="this.media='all'">
The critical CSS system supports multiple extraction strategies depending on your requirements. The size-based strategy extracts CSS rules based on file size thresholds, providing a predictable output size but potentially including rules for below-fold content. The viewport-based strategy extracts only rules that match elements in the visible viewport, producing the smallest critical CSS but potentially missing some above-fold styles if the analysis is incomplete. The hybrid strategy combines both approaches for optimal results.
// Use viewport-based extraction for most aggressive optimization $assets->configureCriticalCss([ 'strategy' => 'viewport', 'viewport_width' => 1280, 'viewport_height' => 800, ]); // Generate critical CSS cache for production if ($assets->isProduction()) { $assets->generateCriticalCss('/css/main.css', '/path/to/page.html'); }
3.7 Security Headers
AssetFlow includes a security headers driver that generates and manages content security policy (CSP) headers, HTTP strict transport security (HSTS), and other security-related response headers. These headers protect your application against common web vulnerabilities including cross-site scripting (XSS), clickjacking, and MIME type sniffing. The security headers system integrates with the existing header rendering pipeline, making it easy to add comprehensive security headers to your application.
$assets = new AssetManager([ 'securityHeadersEnabled' => true, ]); // Configure security headers $assets->configureSecurityHeaders([ 'csp_enabled' => true, 'csp_report_only' => false, 'csp_directives' => [ 'default-src' => ["'self'"], 'script-src' => ["'self'", "'unsafe-inline'", 'https://cdn.example.com'], 'style-src' => ["'self'", "'unsafe-inline'"], 'img-src' => ["'self'", 'data:', 'blob:'], 'font-src' => ["'self'", 'fonts.googleapis.com', 'fonts.gstatic.com'], 'connect-src' => ["'self'", 'https://api.example.com'], ], 'generate_nonce' => true, 'hsts_enabled' => true, 'hsts_max_age' => 31536000, 'x_frame_options' => 'SAMEORIGIN', 'x_content_type_options' => 'nosniff', ]); // Render security headers (call before any output) echo $assets->renderSecurityHeaders();
The CSP system supports nonce-based script and style whitelisting, which provides stronger security than allowing inline scripts. When nonce generation is enabled, AssetFlow generates a unique nonce for each request and includes it in both the CSP header and the inline script/style tags. This approach allows legitimate inline scripts to execute while blocking unauthorized inline scripts injected by attackers.
// Enable nonce-based CSP $assets->configureSecurityHeaders([ 'generate_nonce' => true, 'csp_directives' => [ 'script-src' => ["'self'", "'nonce-{{nonce}}'"], 'style-src' => ["'self'", "'nonce-{{nonce}}'"], ], ]); // Generate headers with nonce $headers = $assets->renderSecurityHeaders(); // Use nonce in inline scripts echo "<script nonce=\"{$assets->getCurrentNonce()}\">\n"; echo " // This script is allowed by CSP\n"; echo "</script>";
3.8 Component Bridge (Vue/React Integration)
The ComponentBridge adapter enables seamless integration of Vue.js and React components within CodeIgniter views. This bridge allows you to render server-side initial states for client-side components, improving SEO and perceived load performance. The adapter handles component registration, prop passing, and hydration configuration through a clean PHP interface.
// Initialize with ComponentBridge adapter $assets = new AssetManager(); $assets->setAdapter('componentbridge'); // Configure Vue.js components $assets->configureComponents([ 'framework' => 'vue', 'root_id' => 'app', 'components' => [ 'Header' => '/js/components/Header.vue', 'Footer' => '/js/components/Footer.vue', 'UserCard' => '/js/components/UserCard.vue', ], 'hydration' => true, 'ssr' => true, ]); // Register a component with props $assets->registerComponent('UserCard', [ 'name' => 'John Doe', 'email' => 'john@example.com', 'avatar' => '/images/avatar.jpg', 'role' => 'admin', ]);
Render the component container and assets in your view. The adapter generates the appropriate HTML structure and JavaScript initialization code for the selected framework. The component will be hydrated on the client side, becoming interactive after the initial server-rendered output loads.
<!DOCTYPE html> <html lang="en"> <head> <?= $assets->renderHead() ?> </head> <body> <div id="app"> <?= $assets->renderComponent('Header') ?> <main class="container"> <?= $assets->renderComponent('UserCard', [ 'name' => 'Jane Smith', 'email' => 'jane@example.com', ]) ?> </main> <?= $assets->renderComponent('Footer') ?> </div> <?= $assets->renderScripts() ?> </body> </html>
For React integration, configure the framework setting accordingly. The adapter generates compatible initialization code and manages the React component lifecycle. Props are serialized as JSON and passed to the React component during initialization.
// Configure React components $assets->configureComponents([ 'framework' => 'react', 'root_id' => 'react-app', 'components' => [ 'Dashboard' => '/js/react/Dashboard.jsx', 'DataChart' => '/js/react/DataChart.jsx', ], 'hydration' => true, 'babel_standalone' => true, ]);
4. Adapter Reference
4.1 Bootstrap 5 Adapter
The Bootstrap 5 adapter provides comprehensive support for the most popular CSS framework. It includes the complete Bootstrap CSS framework and the JavaScript bundle that includes Popper for positioning floating components. The adapter supports all Bootstrap 5.x versions with automatic CSS variable generation for theming. Version management for Bootstrap 5 is straightforward, with the adapter maintaining a mapping of CDN URLs for each supported version including 5.3.2, 5.3.1, 5.3.0, 5.2.3, 5.2.0, 5.1.3, and 5.0.2. The default version is the latest stable release.
$adapter = new \App\Libraries\AssetFlow\Adapters\Bootstrap5(); $adapter->setVersion('5.3.0'); $cssAssets = $adapter->registerCss(true, true); // Returns: ['https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css'] $jsAssets = $adapter->registerJs(true, true); // Returns: ['https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js']
The adapter generates an initialization script that automatically enables Bootstrap's JavaScript components for elements with data attributes. Tooltips, popovers, toasts, and modals are automatically initialized when the DOM is ready. The adapter also supports Bootstrap icons through a separate configuration option.
4.2 Tailwind CSS Adapter
The Tailwind CSS adapter uses the Tailwind Play CDN for development and can be configured to use locally compiled CSS for production deployments. The CDN approach provides immediate access to all Tailwind features without a build step, making it ideal for rapid prototyping and development. Unlike other adapters, Tailwind's CDN script handles CSS through JavaScript at runtime rather than serving pre-built CSS files, which affects how the adapter registers and renders assets.
$adapter = new \App\Libraries\AssetFlow\Adapters\Tailwind(); $adapter->setVersion('3.4.0') ->setTailwindConfig([ 'colors' => [ 'primary' => '#6366f1', 'secondary' => '#8b5cf6', ], ]); $jsAssets = $adapter->registerJs(true, true); // Returns: ['https://cdn.tailwindcss.com']
The adapter supports adding plugins that extend Tailwind's functionality. Plugins are specified as an array of plugin class names or CDN URLs that the Tailwind CDN will load and process. The tailwindConfig can also include custom font families, spacing scales, and other theme extensions supported by the Tailwind CDN.
4.3 Bulma Adapter
Bulma is a modern CSS framework based on Flexbox that provides a clean, lightweight styling foundation. The Bulma adapter provides CSS asset management with support for version switching and theme customization through CSS custom properties. Bulma does not require JavaScript for its components, so the registerJs method returns an empty array. However, the adapter provides an initialization script for common interactive patterns like dropdown toggles and navbar burgers.
$adapter = new \App\Libraries\AssetFlow\Adapters\Bulma(); $adapter->setVersion('1.0.0'); $cssAssets = $adapter->registerCss(true, true); // Returns: ['https://cdn.jsdelivr.net/npm/bulma@1.0.0/css/bulma.min.css']
The adapter also provides a getSassVariables method for generating Sass variable declarations that can be used to compile a custom Bulma build with modified default values. This is useful for projects that need to customize Bulma extensively before deployment.
4.4 Materialize Adapter
Materialize is a responsive front-end material design framework that provides components following Google's Material Design guidelines. The Materialize adapter manages both CSS and JavaScript assets, with the JavaScript bundle including all required dependencies. The adapter includes comprehensive initialization scripts for all Materialize components including parallax, sliders, modals, sidenav, chips, datepickers, timepickers, form selects, scrollspy, and tap targets. The AutoInit method is called automatically to initialize all components with data attributes.
$adapter = new \App\Libraries\AssetFlow\Adapters\Materialize(); $adapter->setVersion('1.0.0'); $cssAssets = $adapter->registerCss(true, true); // Returns: ['https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css'] $jsAssets = $adapter->registerJs(true, true); // Returns: ['https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js']
4.5 ComponentBridge Adapter
The ComponentBridge adapter is an advanced feature that enables integration of Vue.js and React components within CodeIgniter views. This adapter manages framework loading, component registration, and hydration configuration. It bridges the gap between server-side PHP rendering and client-side JavaScript frameworks, enabling hybrid rendering strategies that combine the benefits of both approaches.
$adapter = new \App\Libraries\AssetFlow\Adapters\ComponentBridge(); $adapter->setFramework('vue') ->setVersion('3.4.0') ->setConfig([ 'root_id' => 'app', 'hydration' => true, 'ssr' => true, ]);
The adapter supports both Vue 2 and Vue 3, as well as React. Configuration options control the framework version, component resolution strategy, and hydration behavior. The adapter generates appropriate initialization code based on the selected framework and configuration.
4.6 Creative Adapters
AssetFlow includes three creative adapters that provide distinctive visual aesthetics for specialized use cases. These adapters demonstrate the extensibility of the adapter pattern while providing practical solutions for specific design requirements.
The RetroNES adapter implements 8-bit NES-style UI components using the NES.css library. It includes automatic loading of the Press Start 2P Google Font and provides theme variables for customizing the retro color palette. The adapter also includes a scanline overlay effect and initialization scripts for dialog interactions.
The GlassUI adapter implements modern glassmorphism design with translucent backgrounds, blur effects, and gradient overlays. It includes JavaScript-powered gradient orb animations and hover parallax effects. The adapter supports multiple presets including frost, ice, dark, and neon.
The CyberPunk adapter implements a futuristic cyberpunk aesthetic with neon glows, glitch effects, and sci-fi visual elements. It includes scanline overlay effects, holographic hover interactions, glitch text animations, and typing effects. The adapter supports color presets including classic, matrix, synthwave, tokyo, and arctic.
5. API Reference
5.1 AssetManager Methods
The AssetManager class provides the primary interface for all library operations. Understanding these methods enables you to leverage the full functionality of the library including the core asset management features and advanced production optimization capabilities.
public function __construct(array $configuration = [])
The constructor accepts an optional configuration array that overrides default settings. Configuration options passed here take precedence over values defined in the AssetFlow configuration file. The configuration can include any setting available in the configuration file, allowing runtime customization without modifying global settings.
public function setAdapter(string $name): self
The setAdapter method switches the current UI framework adapter. The adapter name must match a registered adapter, either built-in or custom-registered. Changing the adapter automatically reconfigures all asset generation to use the new framework's assets.
public function setVersion(string $version): self
The setVersion method specifies the framework version to use. The version string must be available in the adapter's version registry. Invalid versions will fall back to the adapter's default version with a warning logged.
public function setTheme(array $theme): self
The setTheme method configures theme variables that are converted to framework-specific CSS custom properties. Theme values are applied to the generated CSS output, enabling runtime theming without requiring style recompilation.
public function addCss(string $path, array $attributes = []): self public function addJs(string $path, array $attributes = []): self
The addCss and addJs methods register additional assets that are included alongside framework assets. Attributes can include standard HTML attributes like media for CSS or defer/async for scripts.
public function defineBundle(string $type, string $name, array $files): self public function registerBundle(string $type, string $name): self
These methods manage asset bundling. Define bundles to group related files together, then register them for inclusion in the output. Bundles are rendered as single optimized files rather than individual assets.
public function configureImageOptimization(array $config): self public function renderImage(string $path, array $attributes = []): string
Image optimization configuration and rendering methods. Configure conversion settings, quality parameters, and responsive breakpoints, then use renderImage to generate optimized HTML with lazy loading and srcset attributes.
public function configureCriticalCss(array $config): self public function generateCriticalCss(string $cssPath, string $htmlPath): string
Critical CSS configuration and generation methods. Configure extraction strategy and inline limits, then generate critical CSS for specific pages or CSS files.
public function configureSecurityHeaders(array $config): self public function renderSecurityHeaders(): string public function getCurrentNonce(): string
Security headers configuration and rendering methods. Configure CSP directives, HSTS settings, and other security headers, then render them as HTTP header output. The getCurrentNonce method returns the current request's CSP nonce for use in inline scripts.
public function configureComponents(array $config): self public function registerComponent(string $name, array $props = []): self public function renderComponent(string $name, array $props = []): string
ComponentBridge configuration and rendering methods for Vue/React integration. Configure the framework and components, register components with their props, and render component containers in views.
public function renderHead(): string
The renderHead method generates all CSS links, meta tags, preconnect hints, theme CSS variables, and inlined critical CSS. This method should be called in the document head for optimal asset loading.
public function renderScripts(): string
The renderScripts method generates all JavaScript tags, CDN fallback scripts, and framework initialization scripts. This method should be called at the end of the document body.
public function renderBodyAttributes(): string
The renderBodyAttributes method returns HTML attribute string for the body element if the current adapter requires any. Some adapters like GlassUI and CyberPunk require specific body classes for their visual effects.
public function clearCache(): self
The clearCache method invalidates all cached asset output, forcing regeneration on the next render call. Call this method after making configuration changes or deploying updates.
5.2 Driver Classes
The Minifier class provides CSS and JavaScript minification functionality. It uses pattern-based minification that is suitable for most use cases without requiring external dependencies. For enhanced minification, the matthiasmullie/minify package can be used as an alternative.
$minifier = new \App\Libraries\AssetFlow\Drivers\Minifier([ 'css' => true, 'js' => true, ]); $minifiedCss = $minifier->minifyCss($rawCss); $minifiedJs = $minifier->minifyJs($rawJs);
The Cacher class manages caching of compiled asset output. It provides methods for storing, retrieving, and invalidating cached content with support for multiple cache backends including file, Redis, and Memcached.
$cacher = new \App\Libraries\AssetFlow\Drivers\Cacher([ 'enabled' => true, 'ttl' => 86400, ]); $cacher->set('cache_key', $htmlOutput); $cachedOutput = $cacher->get('cache_key'); $cacher->delete('cache_key'); $cacher->invalidateAll();
The AssetBundler class manages the concatenation and optimization of multiple assets into efficient bundles. It handles CSS import resolution, JavaScript dependency ordering, and generates source maps for debugging.
$bundler = new \App\Libraries\AssetFlow\Drivers\AssetBundler([ 'output_dir' => 'public/assets/bundles', 'minify' => true, 'source_maps' => true, ]); $bundler->addFiles('css', ['/css/a.css', '/css/b.css'], 'common'); $bundlePath = $bundler->buildBundle('css', 'common');
The ImageOptimizer class handles on-the-fly image conversion, resizing, and format optimization including WebP conversion. It generates responsive image variants and implements lazy loading attributes.
$optimizer = new \App\Libraries\AssetFlow\Drivers\ImageOptimizer([ 'convert_to_webp' => true, 'webp_quality' => 85, 'responsive_breakpoints' => [480, 768, 1024, 1280], ]); $result = $optimizer->optimize('/images/photo.jpg', [ 'max_width' => 800, 'max_height' => 600, ]);
The CriticalCssLoader class extracts and inlines critical CSS for improved first contentful paint performance. It analyzes CSS and HTML to identify the styles needed for above-fold content.
$criticalLoader = new \App\Libraries\AssetFlow\Drivers\CriticalCssLoader([ 'inline_limit' => 10240, 'strategy' => 'size', ]); $criticalCss = $criticalLoader->extract($cssContent, $htmlContent);
The SecurityHeaders class generates and manages content security policy headers and other security-related HTTP headers. It supports nonce generation, CSP reporting, and comprehensive security header configuration.
$security = new \App\Libraries\AssetFlow\Drivers\SecurityHeaders([ 'csp_enabled' => true, 'generate_nonce' => true, 'hsts_enabled' => true, ]); $headers = $security->generateHeaders();
6. Publishing Documentation
6.1 Documentation Structure
The AssetFlow documentation follows a standard documentation structure that enables users to quickly find information and understand library capabilities. The documentation is organized into several key sections that serve different user needs. The Getting Started section provides quick onboarding for new users with installation instructions and basic usage examples. The Configuration section details all available configuration options with explanations of their effects. The Usage section provides comprehensive examples for common scenarios and advanced use cases including asset bundling, image optimization, critical CSS extraction, and security headers. The Adapter Reference section documents each built-in adapter with its specific features and configuration options. The API Reference provides detailed documentation of all public methods and classes including the advanced feature drivers.
When publishing documentation, maintain this structure while adapting examples and explanations to your documentation platform's format. The markdown source files in the repository provide the authoritative documentation content that can be converted to various formats. The documentation should be updated whenever new features are added or existing behavior changes, ensuring users have accurate information for their implementations.
6.2 GitHub Pages Deployment
GitHub Pages is an ideal hosting solution for open source project documentation. It provides free hosting, automatic SSL, and integration with your GitHub repository for easy updates. AssetFlow documentation can be deployed to GitHub Pages using GitHub Actions for automated build and deployment. Create a GitHub Actions workflow file at .github/workflows/docs.yml in your repository to automate documentation deployment.
Enable GitHub Pages in your repository settings by selecting the gh-pages branch as the source. After the first deployment, documentation updates will be automatically deployed when changes are pushed to the main branch. The workflow builds the documentation from source files and deploys it to the gh-pages branch whenever changes are pushed to the main branch.
6.3 Read the Docs Integration
Read the Docs is a documentation hosting platform that provides additional features beyond GitHub Pages including version support, search functionality, and automated builds from various documentation formats. The platform integrates with GitHub and automatically detects documentation updates. Connect your GitHub repository to Read the Docs by importing the project in the Read the Docs dashboard.
The platform will automatically build documentation from the docs directory or the location specified in your configuration. Version support allows you to maintain documentation for multiple release versions simultaneously. Create a mkdocs.yml configuration file in your repository root that defines the documentation structure and theme settings.
7. Contributing
7.1 Reporting Issues
When encountering problems with AssetFlow, first search the existing issues to see if the problem has already been reported. If not, create a new issue with a clear description of the problem, steps to reproduce, expected behavior, and actual behavior. Include relevant environment information such as PHP version, CodeIgniter version, and operating system. For issues related to advanced features like image optimization or security headers, include relevant configuration details and any error messages from your server logs.
For bug reports, provide a minimal code example that demonstrates the issue if possible. This helps maintainers understand and reproduce the problem quickly. For feature requests, explain the use case that motivates the request and how you envision the feature working. Contributions for new adapters, drivers, or advanced features are welcome and should follow the existing code patterns and conventions.
7.2 Submitting Pull Requests
Contributions to AssetFlow are welcome through pull requests on GitHub. Before submitting a pull request, ensure your changes follow the existing code style and include appropriate tests. The library follows PSR-12 coding standards and CodeIgniter 4 conventions. Fork the repository, create a feature branch for your changes, and submit the pull request when ready. Include a clear description of the changes and the problem they solve. Pull requests are reviewed by the maintainer and may require adjustments before being merged.
8. License
AssetFlow is open source software licensed under the MIT license. This license permits use, modification, distribution, and sublicense of the software for both commercial and non-commercial purposes. The license includes the standard MIT permission notice and disclaimer of warranty.
9. Support and Contact
For questions, suggestions, or inquiries about AssetFlow, please contact the author Kazashim Kuzasuwat at kazashimkuzasuwat@gmail.com. The author welcomes feedback on the library's design, documentation, and functionality, as well as contributions from the developer community. Bug reports and feature requests should be submitted through the GitHub issues page to ensure they are tracked and addressed systematically. For general discussion and questions, the GitHub discussions feature provides a forum for community engagement.
AssetFlow Documentation
Author: Kazashim Kuzasuwat
Email: kazashimkuzasuwat@gmail.com
Repository: https://github.com/kazashim/assetflow
Documentation version: 2.0.0
Last updated: January 2026
统计信息
- 总下载量: 0
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 1
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2026-01-02