MVC, PHP and Smarty Caching…

Moving a purely procedural program to an OO design is a mammoth task, especially when that program is several years old and had bits added on over the while.
I’ve pruned out a lot of the extra features that are not needed now, and some that are simply silly, but now I’m coming to a stumbling block.

Smarty can cache content. The beauty of that is I can avoid a whole load of expensive operations like database queries, information lookups from remote sources, code loops, etc. In an MVC application, where should the check for cache freshness be?

  • Should it be in the controller class so it can call the functions of the model to create the view?
  • Should it be in the model, so the controller doesn’t have to know about the model? The model is where the expensive operations are anyway.
  • Should it be in the view, because that’s the locality of freshness information? Isn’t caching an element of the display procedure?

If it’s in the controller, then the controller has to know about caching, is that bad?
If it’s in the model, then the controller is ignorant, and therefore not a controller.
If it’s in the view, the controller is ignorant, and the view is now “controlling” if functions are called in the model.
You can see where my reasoning is going with this..
The controller should probably have access to the cache information. It shouldn’t talk directly to the Smarty instance in the view however. It should talk to a function that takes data from the model, checks the cached views against that data and any timeouts and returns true or false.
For example:

class exampleController
{
  function exampleController()
  {
    // skip unimportant bits.
    // create model and view
    if( $this->view->is_cached() == false )
    {
      // do some expensive operations in
      // the model to create the view.
    }
  }
}

Or should that is_cached() function be in the model? Please comment if you have any insights!

Template Engines

Here’s an interesting article, Template Engines from the author of bTemplate.

In short, the point of template engines should be to separate your business logic from your presentation logic, not separate your PHP code from your HTML code.

That’s the short definition of what a template should do. I think it should also:

  1. Provide application and server security. It could be argued that PHP safe_mode provides a level of security against third-party code.
  2. Make it simple to maintain the template.

In my experience, Smarty syntax is clearer in a html template. Mixing php and html grates on my brain but obviously it’s a subjective matter that many people are happy with.
Nevertheless, if you’re sitting on the fence about using templates, read the above article. See what the author does in his examples, and make up your own mind if they’re useful or not. You might find yourself using Smarty afterwards anyway!