Lift snippet selection - DispatchSnippet vs snippet reflection
July 20th, 2009
One of the confusing things about Lift for new comers are snippets – not only conceptually, but the bewildering array of options they have when choosing snippet implementation style. Users have to choose between snippet reflection, dispatch snippets and even statefull snippets that extend snippet dispatching!
Reflection Snippets
Loading class-based snippets via reflection is the default scheme in Lift as it offers a quick start for development. Given the following code in my snippet package:
import _root_.scala.xml.{NodeSeq,Text}
class HelloWorld {
def speak = <span>Hello World</span>
}
I could then just call this in any Lift template I wanted by using the following:
<lift:hello_world.speak />
So right there, with no other plumbing we have a working snippet invocation – granted, our example is not feature full but it services our needs for this example. So this is all great, and works perfectly for development / low volume deployment, however when your site starts to scale this method of snippet modeling will become undesirable. Why? Every time you call the reflection snippet in your markup code, a new instance is instantiated and the appropriate method invoked – of course, if you have lots of the same snippet in a single page request cycle this is less than desirable (not to mention if said page is getting thousands of requests)
DispatchSnippet to the rescue!
In Scala we can of course use the object keyword to create a singleton object – this is most helpful in terms of snippets, as comparatively to creating lots of instances, here we will only have a single one which makes for a much more optimal snippet system. Lets take our previous snippet and turn it into a dispatch snippet:
import _root_.scala.xml.{NodeSeq,Text}
import _root_.net.liftweb.http.DispatchSnippet
object HelloWorld extends DispatchSnippet {
def dispatch = {
case "talk" => speak
}
def speak = <span>Hello World</span>
}
There is of course a slight downside – the reflection snippets mean no plumbing, but with the DispatchSnippet we will of course just need to let Lift know when we call something in our XHTML what snippet instance we are referring to – we do this with a SnippetDispatchPF call in your Boot.scala file:
LiftRules.snippetDispatch.append(
Map("hello_world" -> HelloWorld)
)
This means in our XHTML we can call:
<lift:hello_world.talk />
This has the exact same output as the reflection style snippet, but only using a single snippet instance for your application.
Sorry, comments are closed for this article.