[nycphp-talk] JSON and MVC
Chris Snyder
chsnyder at gmail.com
Wed Jul 15 14:22:11 EDT 2009
On Wed, Jul 15, 2009 at 12:35 PM, Hans Zaunere<lists at zaunere.com> wrote:
> But what would a template for this look like? What I'm having trouble streamlining is what those actual templates look like. They're not outputting dynamically generated text anymore, per se. They're outputting low level data structures (like an array) which classic templating doesn't seem to jive with.
So say I want to end up with a series of messages that look like:
<div id="Messages">
<div id="messageid" class="message">
<h3>Message Subject</h3>
<p>Posted by Author on Date</p>
<div class="content">
Lorem ipsum dolor sit amet...
</div>
</div>
...
</div>
So I create a template function that renders a message from a data
structure (obj) and attaches it to some container element (using
MochiKit DOM functions):
// template / view
// note, this code assumes that data properties already been html escaped...
function appendMessageFromData( element, data ) {
var newDOM = DIV(
{"id": data.id, "class": "message"},
H3( data.subject ),
P( "Posted by " + data.author + " on " + data.date ),
DIV( {"class": "content"}, data.content )
);
element.appendChild( newDOM );
}
// controller
//var messages = loadJSONDoc(url);
var messages = [
{ "id": "123abc", "subject": "First Post", "author": "Hans Zaunere",
"date": "July 15, 2009", "content": "Lorem ipsum dolor sit amet" },
...
];
// append messages to #Messages
for( var i=0; i<messages.length; i++ ) {
appendMessageFromData( $('Messages'), messages[i] );
}
>
> The quick correlation to existing template methodology, in my opinion, would be to build the JSON "markup" directly, just like we've done for HTML/XML, using presentation logic and the template engine. For example something roughly like this:
>
> ["
> <?php foreach( $Messages as $M ): ?>
> {\"MessageGID\":\"<?=$M->MessageGID?>\",
> \"LRGID\":\"<?=$M->LRGID?>\",
> \"AccountGID\":\"<?=$M->AccountGID?>\",
> \"Status\":<?=$M->Status?>},
> \"mi_\":\"<img src=\\\"<?=$M->ImgSrc?>" \\\/>\"
> <?php endforeach; ?>
> "]
>
But that's harder than just building an array of key=>value pairs and
then calling json_encode(). Think of JSON as the Model in MVC. You PHP
code is exporting the data model to this other MVC app that runs on
the client.
I don't get why you'd want to do everything on the server? Offloading
it to the client is a little harder to get right, but it scales like
crazy once you do.
More information about the talk
mailing list