phpcompressioncode-generationgoogle-closure-compiler

How to write PHP code that repeats itself per array value


I'm using Closure Compiler to compress and join a few JavaScript files the syntax is something like this;

$c = new PhpClosure();
$c->add("JavaScriptA.js")
  ->add("JavaScriptB.js")
  ->write();

How could I make it systematically add more files from an array? Let's say for each array element in $file = array('JavaScriptA.js','JavaScriptB.js','JavaScriptC.js',..) it would execute the following code

$c = new PhpClosure();    
$c->add("JavaScriptA.js")
  ->add("JavaScriptB.js")
  ->add("JavaScriptC.js")
  ->add
  ...
  ->write();

Solution

  • The PhpClosure code uses method chaining to reduce repeated code and make everything look slightly nicer. The functions (or at least the add function) returns $this (The object the function was called on).

    The code in the first sample could be written as:

    $c = new PhpClosure();
    $c->add("JavaScriptA.js");
    $c->add("JavaScriptB.js");
    $c->write();
    

    The middle section (The add function calls) can then be transformed so that it loops over an array of files rather than having to add a line for each file.

    $files = array("JavaScriptA.js", "JavaScriptB.js");
    $c = new PhpClosure();
    foreach ( $files as $file ){
        $c->add($file);
    }
    $c->write();