Skip to content

Repository files navigation

Assetic

Average time to resolve an issuePercentage of issues still open

Assetic is an asset management framework for PHP maintained by the Winter CMS team.

<?phpuseAssetic\Asset\AssetCollection;
useAssetic\Asset\FileAsset;
useAssetic\Asset\GlobAsset;
$js = newAssetCollection(array(
newGlobAsset('/path/to/js/*'),
newFileAsset('/path/to/another.js'),
));
// the code is merged when the asset is dumpedecho$js->dump();

Assets

An Assetic asset is something with filterable content that can be loaded and dumped. An asset also includes metadata, some of which can be manipulated and some of which is immutable.

PropertyAccessorMutator
contentgetContentsetContent
mtimegetLastModifiedn/a
source rootgetSourceRootn/a
source pathgetSourcePathn/a
target pathgetTargetPathsetTargetPath

The "target path" property denotes where an asset (or an collection of assets) should be dumped.

Filters

Filters can be applied to manipulate assets.

<?phpuseAssetic\Asset\AssetCollection;
useAssetic\Asset\FileAsset;
useAssetic\Asset\GlobAsset;
useAssetic\Filter\LessFilter;
useAssetic\Filter\UglifyCssFilter;
$css = newAssetCollection(array(
newFileAsset('/path/to/src/styles.less', array(newLessFilter())),
newGlobAsset('/path/to/css/*'),
), array(
newUglifyCssFilter('/path/to/uglifycss'),
));
// this will echo CSS compiled by LESS and compressed by uglifycssecho$css->dump();

The filters applied to the collection will cascade to each asset leaf if you iterate over it.

<?phpforeach ($cssas$leaf) {
// each leaf is compressed by uglifycssecho$leaf->dump();
}

The core provides the following filters in the Assetic\Filter namespace:

  • CoffeeScriptFilter: compiles CoffeeScript into Javascript
  • CssImportFilter: inlines imported stylesheets
  • CssMinFilter: minifies CSS
  • CssRewriteFilter: fixes relative URLs in CSS assets when moving to a new URL
  • GoogleClosure\CompilerApiFilter: compiles Javascript using the Google Closure Compiler API
  • HandlebarsFilter: compiles Handlebars templates into Javascript
  • JpegoptimFilter: optimize your JPEGs
  • JpegtranFilter: optimize your JPEGs
  • JSMinFilter: minifies Javascript
  • JSMinPlusFilter: minifies Javascript
  • JSqueezeFilter: compresses Javascript
  • LessFilter: parses LESS into CSS (using less.js with node.js)
  • LessphpFilter: parses LESS into CSS (using lessphp)
  • OptiPngFilter: optimize your PNGs
  • PackerFilter: compresses Javascript using Dean Edwards's Packer
  • PhpCssEmbedFilter: embeds image data in your stylesheet
  • ReactJsxFilter: compiles React JSX into JavaScript
  • ScssphpFilter: parses SCSS into CSS
  • SeparatorFilter: inserts a separator between assets to prevent merge failures
  • StylusFilter: parses STYL into CSS
  • TypeScriptFilter: parses TypeScript into Javascript
  • UglifyCssFilter: minifies CSS
  • UglifyJs2Filter: minifies Javascript
  • UglifyJs3Filter: minifies Javascript

Asset Manager

An asset manager is provided for organizing assets.

<?phpuseAssetic\AssetManager;
useAssetic\Asset\FileAsset;
useAssetic\Asset\GlobAsset;
$am = newAssetManager();
$am->set('jquery', newFileAsset('/path/to/jquery.js'));
$am->set('base_css', newGlobAsset('/path/to/css/*'));

The asset manager can also be used to reference assets to avoid duplication.

<?phpuseAssetic\Asset\AssetCollection;
useAssetic\Asset\AssetReference;
useAssetic\Asset\FileAsset;
$am->set('my_plugin', newAssetCollection(array(
newAssetReference($am, 'jquery'),
newFileAsset('/path/to/jquery.plugin.js'),
)));

Filter Manager

A filter manager is also provided for organizing filters.

<?phpuseAssetic\FilterManager;
useAssetic\Filter\ScssFilter;
useAssetic\Filter\CssMinFilter;
$fm = newFilterManager();
$fm->set('sass', newScssFilter('/path/to/parser/scss'));
$fm->set('cssmin', newCssMinFilter());

Asset Factory

If you'd rather not create all these objects by hand, you can use the asset factory, which will do most of the work for you.

<?phpuseAssetic\Factory\AssetFactory;
$factory = newAssetFactory('/path/to/asset/directory/');
$factory->setAssetManager($am);
$factory->setFilterManager($fm);
$factory->setDebug(true);
$css = $factory->createAsset(array(
'@reset', // load the asset manager's "reset" asset'css/src/*.scss', // load every scss files from "/path/to/asset/directory/css/src/"
), array(
'scss', // filter through the filter manager's "scss" filter'?cssmin', // don't use this filter in debug mode
));
echo$css->dump();

The AssetFactory is constructed with a root directory which is used as the base directory for relative asset paths.

Prefixing a filter name with a question mark, as cssmin is here, will cause that filter to be omitted when the factory is in debug mode.

You can also register Workers on the factory and all assets created by it will be passed to the worker's process() method before being returned. See Cache Busting below for an example.

Dumping Assets to static files

You can dump all the assets an AssetManager holds to files in a directory. This will probably be below your webserver's document root so the files can be served statically.

<?phpuseAssetic\AssetWriter;
$writer = newAssetWriter('/path/to/web');
$writer->writeManagerAssets($am);

This will make use of the assets' target path.

Cache Busting

If you serve your assets from static files as just described, you can use the CacheBustingWorker to rewrite the target paths for assets. It will insert an identifier before the filename extension that is unique for a particular version of the asset.

This identifier is based on the modification time of the asset and will also take depended-on assets into consideration if the applied filters support it.

<?phpuseAssetic\Factory\AssetFactory;
useAssetic\Factory\Worker\CacheBustingWorker;
$factory = newAssetFactory('/path/to/asset/directory/');
$factory->setAssetManager($am);
$factory->setFilterManager($fm);
$factory->setDebug(true);
$factory->addWorker(newCacheBustingWorker());
$css = $factory->createAsset(array(
'@reset', // load the asset manager's "reset" asset'css/src/*.scss', // load every scss files from "/path/to/asset/directory/css/src/"
), array(
'scss', // filter through the filter manager's "scss" filter'?yui_css', // don't use this filter in debug mode
));
echo$css->dump();

Internal caching

A simple caching mechanism is provided to avoid unnecessary work.

<?phpuseAssetic\Asset\AssetCache;
useAssetic\Asset\FileAsset;
useAssetic\Cache\FilesystemCache;
useAssetic\Filter\JsMinFilter;
$jsMin = newJsMinFilter();
$js = newAssetCache(
newFileAsset('/path/to/some.js', array($jsMin)),
newFilesystemCache('/path/to/cache')
);
// the JsMin compressor will only run on the first call$js->dump();
$js->dump();
$js->dump();

Twig

To use the Assetic Twig extension you must register it to your Twig environment:

<?php$twig->addExtension(newAsseticExtension($factory));

Once in place, the extension exposes a stylesheets and a javascripts tag with a syntax similar to what the asset factory uses:

{%stylesheets'/path/to/sass/main.sass'filter='sass,?yui_css'output='css/all.css'%}
<linkhref="{{ asset_url }}"type="text/css"rel="stylesheet" />
{%endstylesheets%}

This example will render one link element on the page that includes a URL where the filtered asset can be found.

When the extension is in debug mode, this same tag will render multiple link elements, one for each asset referenced by the css/src/*.sass glob. The specified filters will still be applied, unless they are marked as optional using the ? prefix.

This behavior can also be triggered by setting a debug attribute on the tag:

{%stylesheets'css/*'debug=true%} ... {%stylesheets%}

These assets need to be written to the web directory so these URLs don't return 404 errors.

<?phpuseAssetic\AssetWriter;
useAssetic\Extension\Twig\TwigFormulaLoader;
useAssetic\Extension\Twig\TwigResource;
useAssetic\Factory\LazyAssetManager;
$am = newLazyAssetManager($factory);
// enable loading assets from twig templates$am->setLoader('twig', newTwigFormulaLoader($twig));
// loop through all your templatesforeach ($templatesas$template) {
$resource = newTwigResource($twigLoader, $template);
$am->addResource($resource, 'twig');
}
$writer = newAssetWriter('/path/to/web');
$writer->writeManagerAssets($am);

Assetic is based on the Python webassets library (available on GitHub).

About

Asset Management for PHP

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages