Skip to content

Instantly share code, notes, and snippets.

@pgraham
Created August 11, 2012 00:10
Show Gist options
  • Save pgraham/3319193 to your computer and use it in GitHub Desktop.
Save pgraham/3319193 to your computer and use it in GitHub Desktop.
Package structure for javascript files which allows them to be written modularly but easily compiled into large scripts for more efficient page loading.
<?php
/**
* Class which compiles web resources composed of multiple files into larger files for quicker
* page loading.
*
* The compilation happens based on a conventional package structure which is defined by the file system
* containing the source. The root of the file system containing the packages only contains directories.
* Each directory in the root is itself the root of a set of hierarchical packages.
*
* Packages are referred use a dot (.) notation similar to Java. Compilation will produce one file per
* package which is the amalgamation of all resource files and sub-packages in the package. The order of
* the resources files in the amalgamation is undefined beyond that sub-packages will appear before
* resource files. Each package may contain three special files that have a guaranteed order in the
* compiled package.
*
* + __init.<resource_type> will appear at the beginning of the package.
* + __postSubPackage.<resource_type> will appear after all sub-packages and before any resource files.
* + __ready.<resource_type> will appear at the end of the package.
*
* ## Flat package example
*
* ### Source file structure
* /source-root
* /pkg1
* /__init.js
* /__ready.js
* /file1.js
*
* ### Target output
* /target
* /pkg1.js
*
* ### /source-root/pkg1/__init.js
* (function (/*...*/) {
* // Do something before any other files are loaded
* } (/*...*/));
* ### /source-root/pkg1/__ready.js
* (function (/*...*/) {
* // Do something after all resources are loaded
* } (/*...*/));
* ### /source-root/pkg1/file1.js
* (function (/*...*/) {
* // Provide some functionality
* } (/*...*/));
* ### /target/pkg1.js
* (function (/*...*/) {
* // Do something before any other files are loaded
* } (/*...*/));
* (function (/*...*/) {
* // Provide some functionality
* } (/*...*/));
* (function (/*...*/) {
* // Provide some functionality
* } (/*...*/));
*
* ## Sub package example
*
* @author Philip Graham <philip@zeptech.ca>
*/
class ResourcePackageCompiler {
private $_resourceType;
public function __construct($resourceType = 'js') {
$this->_resourceType = $resourceType;
}
public function compile($src, $target) {
$this->_ensureTarget($target);
}
private function _ensureTarget($target) { /* Ensure target directory exists and is writeable */ }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment