Sunday, January 25, 2009

Using Image_Graph neatly

Here are my two best tips around using Image_Graph for projects. They aren't necessarily right, but have worked fantastically for me.

Use it like Google Chart API (on demand)

Build a simple page which takes a number of arguments via GET variables, and serves up an image. You can then use simple commands to render whatever you like.

# Rendering code:
require_once 'Net/URL.php';
function make_graph_url($data) {

$url = new Net_URL('graph.php');
$url->gt;querystring['data'] = $data;
$url->gt;querystring['type'] = 'pie';
return $url->gt;getURL(); // "graph.php?type=pie&data[Cats]=1&data[Fish]=2";

# HTML / Presentation bit
<img src="%3C?php%20print%20make_graph_url%28$data%29;%20?%3E" alt="Graph of Cats and Fish" />

require_once 'Image/Graph.php';

$graph = new Image_Graph();
// read in $_GET and construct your graph


Its worth thinking about maintaining a pretty similar approach to google's API, so that you can swap one for the other almost trivially.


Say you have a set of reports you must run. The amount of data is huge, so you really don't want to try and do things on the fly. You have to update the data periodically - ie, once a week or month.

Steps here:
1. Denormalize in the database - precalculate answers and render them into tables. It will save you loads of time.
2. When you have the data you need, pre-render the graphs and save them to disk. Do it with an easy naming scheme.

Now when someone hits your pages to look at information, you've got everything already there - its a matter of wiring it together.

These two things are pretty obvious and self explanatory, but worth keeping in mind. The last thing you want to do is build a page which assembles data, then realize Image_Graph renders in a different stream (ie, not inline), and resort to copy and paste coding.

Reblog this post [with Zemanta]

No comments: