Home arrow AJAX & Prototype arrow Google's Closure Compiler Service API: Fundamentals

Google's Closure Compiler Service API: Fundamentals

Looking for a fast way to optimize your JavaScript files, but don't want to give up total control? Google offers Closure Compiler, which makes use of an intuitive REST API and several other features to get you exactly the optimization you need for your JavaScript.

  1. Google's Closure Compiler Service API: Fundamentals
  2. Adding a method to perform HTTP requests
By: Alejandro Gervasio
Rating: starstarstarstarstar / 1
September 28, 2010

print this article



The web has become a dynamic creature in permanent evolution that is changing faster and faster all the time. This statement is more than a simple metaphor since it can be interpreted literally: considering the large number of JavaScript libraries available nowadays, it’s not surprising that more and more websites use them extensively. This process generates tons of JavaScript files, which in many cases are heavier that the markup itself. Does this scenario ring any bells for you? I bet it does.

Of course, you might argue that the situation isn’t so critical after all, as many of these libraries, including jQuery, Mootools, Dojo and Prototype (feel free to add your own one to the list) also provide minified and compressed versions, which are quicker to download and cache. While I have to say that you’re right, things can get much more complex when you need to optimize custom JavaScript code. The process can be tedious, time-consuming and extremely annoying, especially if you plan to tackle it manually.

Although it’s fair to admit that currently there are some websites that offer free optimization of CSS and JavaScript files, either via a copy/paste procedure or by specifying the URLs of the files, the truth is that only a few of them will let you perform the optimization process programmatically. However, not all is lost, since in this apparently arid and pessimistic panorama, Google shines a hopeful light, with quite impressive results. The company has released a brand new web service called Closure Compiler (http://code.google.com/intl/en/closure/compiler/docs/overview.html) which will automatically optimize your JavaScript files by means of an intuitive REST API that can be consumed by any server-side programming language. What’s more, the service has several options that allow you to control certain things either manually or programmatically, such as the level of optimization applied to the target files, the format in which they’ll be delivered to the client (text, XML or JSON) and what kind of information will be displayed on screen (compiled code, statistics and so forth).

Provided that the topic has already caught your attention and you’re interested in learning how to work with Google's Closure Compiler Service API, in this article series I’m going to show you how to interact with the API using some PHP classes. All the examples that you will see in the tutorials, however, can be easily adapted to function with the language of your choice, trust me.

Now, it’s time to start digging deeper into the features provided by the aforementioned Closure Compiler Service API. Let’s get going!

Setting the scenario to interact with Google’s Closure Compiler Service API: building an abstract HTTP request handler PHP class

As I expressed in the introduction, my goal here is to show in a step-by-step fashion how to consume Google’s Closure Compiler Service API by using a few sample PHP classes. This shouldn’t stop you, however, from giving the API a try through its UI, which can be found here. All that you’ll need to do is paste into the corresponding text area the code of the JavaScript file that you want to compile (or its URL), and then select the appropriate compiling options. The results will be displayed on the right-placed tab. The whole process is that easy, really.

Having clarified that, it’s time to get our hands dirty and start creating the PHP classes that will interact with the Closure Compiler. Since the compiler’s API must be queried via a POST HTTP request, I will first define an abstract class capable of triggering HTTP requests to a specified host on a given TCP port.

With that said, here’s the definition of this abstract class at its initial stage:



abstract class HttpRequestHandlerAbstract
    protected $_data = array();
    protected $_url;
    protected $_port;
    protected $_method;
    protected $_headers = array();
    protected $_responseHeader;
    protected $_responseContent;
    // constructor
    public function __construct(array $data, array $settings = array())
        if (array_key_exists('url', $settings)) {
        if (array_key_exists('port', $settings)) {
        if (array_key_exists('method', $settings)) {
    // set the data that will be passed with the request
    public function setData(array $data)
        if (empty($data)) {
            throw new HttpRequestHandlerException('The request arguments are not valid.');
        $this->_data = $data;
        return $this;
    // get the specified request data
    public function getData()
        return $this->_data;
    // set the URL the request will be made to (implemented by subclasses)
    abstract public function setUrl($url);
    // get the given URL
    public function getUrl()
        return $this->_url;
    // set the TCP port the request will be made on (implemented by subclasses)
    abstract public function setPort($port);
    // get the given port
    public function getPort()
        return $this->_port;
    // set the request method (GET or POST)
    public function setMethod($method = 'GET')
        $method = strtoupper($method);
        if (!in_array($method, array('GET', 'POST'), TRUE)) {
            throw new HttpRequestHandlerException('The request method is not valid.');
        $this->_method = $method;
        return $this;
    // get the request method
    public function getMethod()
        return $this->_method;
    // add a new request header
    public function addHeader($key, $header)
        $key = strtolower($key);
        if (!array_key_exists($key, $this->_headers)) {
            $this->_headers[$key] = $header;
        return $this;
    // remove a specified request header
    public function removeHeader($key)
        $key = strtolower($key);
        if (array_key_exists($key, $this->_headers)) {
        return $this;
    // get a specified request header
    public function getHeader($key)
        $key = strtolower($key);
        if (array_key_exists($key, $this->_headers)) {
            return $this->_headers[$key];
    // get the header included in the response
    public function getResponseHeader()
        return $this->_responseHeader;
    // get the content included in the response
    public function getReponseContent()
        return $this->_responseContent;
    // send the specified header
    public function sendHeader($key)
        if ($header = $this->getHeader($key)) {



class HttpRequestHandlerException extends Exception{}

Even though at first glance the above “HttpRequestHandlerAbstract” class seems to be complicated, this is only a misleading impression. Its driving logic is quite easy to follow. Simply put, the class implements a few straightforward methods for adding, removing and getting request headers, and for sending them explicitly as well. In addition, the class accepts, via its constructor (or alternatively via its mutator methods), an array of data containing the parameters that will be passed along with the request, together with the corresponding URL and the TCP port.

It’s valid to note that the methods that set the URL and TCP port associated with the request have been declared abstract. This is done so that they’ll be implemented by a concrete subclass. This subclass will be responsible for talking directly to the Closure Compiler API, in this way taking advantage of the refined functionality provided by Inheritance. Got that point? Great.

In its current state, the previous abstract class is capable of handling most of the options required for triggering an HTTP request to a given host on a specific TCP port, but it still lacks a method that performs the actual requests. Fortunately, this issue can be solved in a snap. To prove that, in the following section I’m going to show you the full implementation of this pending method.

Now, click the link below and keep reading.

>>> More AJAX & Prototype Articles          >>> More By Alejandro Gervasio

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Best AJAX Tutorials for Forms
- The Best AJAX Tutorials
- 8 Great Ajax Tutorials
- Using Ajax and jQuery
- Using Ajax and jQuery with HTML Forms
- Ajax.org Offers Cloud9 IDE for JavaScript
- Java Technologies Provider ICEsoft Releases ...
- Using Recaptcha in AJAX Prototype Framework ...
- Google's Closure Compiler Service API: Addit...
- Installing Google Web Toolkit: Introducing t...
- Google's Closure Compiler Service API: Displ...
- Google's Closure Compiler Service API: Deliv...
- Google's Closure Compiler Service API: the A...
- Google's Closure Compiler Service API: the S...
- Google's Closure Compiler Service API: Optim...

Developer Shed Affiliates


Dev Shed Tutorial Topics: