SVG as your MVC View

Lately, I’ve been playing with the SVG format - a W3C backed XML format for Scalable Vector Graphics. Firefox can now render SVG natively, and this opens the door for lots of fun things you can do with it.

There are already very nice implementations of PHP classes that, for example, generate nice graphs using SVG - although I’ve never used it, the eZ Components Graph module is a very good example.

However, if you are looking to generate graphics dynamically from a pre-built template, you don’t really need to use any libraries or heavy OO and XML abstractions. Since SVG is just another type of XML, just like XHTML, using PHP to generate dynamic SVG is quite intuitive. Looking at this from an MVC perspective, you can think of SVG as yet another form of view for data - and it can be quite easily used as a “template” just like XHTML is used.
It is also quite easy to embed SVG into XHTML or vice-versa - but this means that you will need an SVG capable browser in order to render the page (did I already mention Firefox is one?)

I am still playing around with the format and with the whole concept - but in the mean time, here is a (non-scalable png) screenshot of an SVG graph I generated using simple PHP code:

SVG Graph

You can see how this graph is embedded within XHTML and generated here - it also shows the entire source code. A few notes though:

  1. I have no idea how other browsers render this. It works with Firefox - I’m quite sure IE (even 7.0) does not render SVG without special plugins
  2. Pay attention to the header() call - it’s important!
  3. The use of Zend Framework is there only for fetching the data from digg - the real stuff doesn’t rely on Zend Framework

If I have enough time (and I’m able to get myself to focus ;) ) I’ll study this some more and maybe build some nice tutorial.

3 Responses to “SVG as your MVC View”

  1. March 25th, 2007 | 20:14

    Opera 9+ should render XHTML+SVG as well. Safari nightlies should also not have a problem.

    IE7- will not render your XHTML+SVG example, regardless of any plugin you use because it has no native support for SVG (or XHTML, for that matter). You can download the Adobe SVG plugin, but that will only work for HTML with SVG embedded (using the HTML:object entity).

    See http://www.codedread.com/displayWebStats.php for an example of this.

  2. March 25th, 2007 | 21:30

    If the Adobe plugin needs the html:object tag, I think it’s no problem adding it.

    Besides, I think this is a useful idea even without full browser support - you can always allow the user to download the SVG graphs and use an external software to view them, or even convert the SVG on the server side to some embeddable image if you really want to.

  3. March 25th, 2007 | 21:35

    BTW Jeff: Your sample is amazing! Doesn’t perform great in Firefox (as you mentioned) but the concept (especially the interactivity) is great.