I am a programmer and architect (the kind that writes code) with a focus on testing and open source; I maintain the PHPUnit_Selenium project. I believe programming is one of the hardest and most beautiful jobs in the world. Giorgio is a DZone MVB and is not an employee of DZone and has posted 638 posts at DZone. You can read more from them at their website. View Full User Profile

Assetic: JavaScript and CSS files management

08.04.2011
| 13584 views |
  • submit to reddit

Assetic is a PHP library for managing the deployment of your assets: JavaScript, CSS and other resources which will be requested by the browser. The library has been created by Kris Wallsmith from OpenSky, an e-shop where many of the active members of the PHP community work, or worked (see Jonathan Wage/Doctrine 1 and Bulat Shakirzyanov/Imagine.)

How assets are deployed

As the most basic option, assets files can be just moved in a public folder in your document root, so that they are accessible directly via an HTTP request. The usage of <script> and <link> tags will link your web pages to these files.

Alternatively, you can introduce a compilation-like step between the original files and what gets deployed in the public folder: Assetic implements this intermediate step.
Why adding a further step to deployment? Until you are in the development environment, most of the time there's no difference between the original files and what you can build from them with Assetic and similar libraries. But even if there are no functional differences, we can say there are some non-functional ones:

  • the browser has to request many different files, adding the overhead of requests to each.
  • The browser has to receive unnecessary traffic, comprehending the spaces, tabs and other code-formatting characters that it doesn't care for.

What you can do with Assetic?

You can build a single file for all the resources of the same type (JavaScript, CSS) and output the result. The browser will only have to request one large file, which will be easily cached. In this scenario, you move the complexity of the <script> tags into PHP code, which you may be more familiar with; ans as you'll see, it's really simple to just string together all the files in a directory tree.

The intermediate step can perform minification over the single files, with many different back ends. You always write nicely formatted JavaScript code, but before being sent on the network this code is compressed on a single line in a very unreadable but shorter form.

The intermediate step also enables you to perform compilation from an higher-level language to JavaScript and CSS. SASS and CoffeeScript - languages which are included by default in Rails 3.x - are examples of abstraction over the. If you want to develop in this languages, Assetic ensures that each file is compiled to something the browser can read.

Note that both SASS and CoffeeScript compilation respectively rely on the presence of the sass and coffee (with node) binaries. Many other filters assume the presence of JARs and other external libraries whose path you can specify and that may be invoked by the user running, being it a webserver or a deployment process. The policy of Assetic is provide an uniform PHP Api to these external libraries, not recompiling the wheel.

An example

I set up three small JavaScript files, each containing a single line. Here's how I made Assetic merge them:

<?php
use Assetic\Asset\AssetCollection;
use Assetic\Asset\FileAsset;
use Assetic\Asset\GlobAsset;

/**
 * I have included the tests bootstrap for simplicity, but if you have a PSR-0
 * autoloaders (standard for Zend Framework or Symfony) you can use that.
 */
require_once __DIR__ . '/tests/bootstrap.php';

/**
 * I take the example of the documentation and add real files.
 */
$javascriptCode = new AssetCollection(array(
    new GlobAsset('js-always-to-be-included/*'),
    new FileAsset('additional.js')
));

echo $javascriptCode->dump();

The result is a single string:

[10:46:01][giorgio@Desmond:~/code/assetic]$ php test.php
myjs = {};

myjs.method = function() {};

myjs.otherMethod = function() {};

I also tried minifying it by using a public Google Api, in order for this process to work out of the box:

use Assetic\Filter\GoogleClosure\CompilerApiFilter;

$javascriptCode = new AssetCollection(array(
    new GlobAsset('js-always-to-be-included/*'),
    new FileAsset('additional.js')
), array(
    new CompilerApiFilter()
));

echo $javascriptCode->dump();

Not even the final \n character is left after compression.

[10:47:05][giorgio@Desmond:~/code/assetic]$ php test_filter.php
myjs={};
myjs.method=function(){};
myjs.otherMethod=function(){};[10:47:43][giorgio@Desmond:~/code/assetic]$

As you can see, a script using Assetic objects may just output a result that your HTTP server can cache (if you place the script in a public directory). An alternative is to write the result to files which will be placed in this directory: Assetic/AssetWriter is the right tool for this job. In the latter case, you also have more control on the invalidation of the deployed code, as just substituting the file in your deployment process will update the copy served by the web server.

Published at DZone with permission of Giorgio Sironi, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Alex Objelean replied on Thu, 2011/08/04 - 2:51pm

For java there is the wro4j library, which besides assets management brings a dozen of other features like: coffeeScript, lessCss, sassCss, jsHint, cssLint integration and many others.

Giorgio Sironi replied on Fri, 2011/08/05 - 4:12am

Thank you for your addition. As the complexity of web development goes up, we need this kind of tools to be available for each language.

Erik Wiesenthal replied on Wed, 2011/08/10 - 11:02am

There is a php library, so old and forgotten, but i managed to adapt it to zf and my own framework. http://aciddrop.com/php-speedy/ It needs some php5 tweaks, some design changes, some updates in libraries (jsmin...) But after it it does a great job. The library merge your scripts and css, reading it from the obcache, minimice and comprime all and write it to a file, using md5 string to identify changes. It writes headers for browser cache, refresh, etc.... A great library

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.