Skip to content
This repository has been archived by the owner on Nov 27, 2018. It is now read-only.

What Happens Under the Hood

klanoma edited this page Mar 24, 2013 · 4 revisions

If you want to customize Punch, it's better to have an idea of what happens under the hood.

Punch is composed of small, self-contained modules that communicate with each other. Once you understand how they are interfaced, you can easily mix and match them the way you want. For example, you can write a custom template handler that works with Punch's renderer or even use the renderer in a custom server implementation.

Best way to explore Punch's internals would be to read the source and specs. You can find a full list of Punch's modules here.

Here's a high level overview of how the main components works.

Renderer

Renderer is the heart of Punch. When a request (a URL) is passed to renderer, it will try to respond to the request, in this order:

  • With a static resource available in templates that directly matches to the request. (eg. if you request /favicon.ico, it will serve the templates/favicon.ico)
  • With a resource available in templates that can be compiled to the request type. (eg. if you request /assets/styles.css, and there's a templates/assets/styles.less; it will compile and serve the LESS file.)
  • With the rendered output of a matching layout and content (enhanced with helpers). (eg. if you request /products/tshirt.html, Punch will render the content available in contents/products/tshirt.json using the layout templates/products/_layout.mustache)
  • With an error page (templates/404.html), if non of the above could be found.

If you got a cached copy of the response, you can send its timestamp to renderer along with the request. Then renderer will only provide a response if the resources has been modified since the cached version.

Server

Punch's server is a regular HTTP server built using Connect middleware. It uses default middelware to handle cookies, compressions and logging. Apart from that it uses a Punch specific middleware that interfaces with Punch's renderer and cache store.

Basically, the server forwards clients' requests to renderer and renderer's responses to the client. In between, it also manages the cache store. When a request comes in, server will notify the renderer the latest available response in the cache store and if the renderer says response hasn't modified; it will serve the cached response.

Generator

Generator can be used to prepare a site ahead of time. It also works similar to the server, but it prefetches all available paths and stores the rendered pages in the cache (which is by default a directory). Then you can serve the contents in the cache directory as static files using any common web server. You can write hooks to run after generating each file.