Following on from previous posts on PHP and MVC and in particular on using Smarty caching in the MVC design pattern, I used Smarty to cache the output of an app at work this morning.
I agonised in my last post about where to put the caching, should it go into the viewer, or the model, or the controller?
- I finally decided to make the viewer responsilble for deciding if the template is cached or not.
- The controller then asks the viewer if the current page is cached, if it’s not, then it runs whatever functions the model needs to generate the page.
class mvcViewer
{
function mvcViewer()
{
$this->cacheKey = md5( $_SERVER[ 'REQUEST_URI' ] );
}
function display()
{
// modified to use the cacheKey.
$this->assign();
$this->smarty->display( $this->formTplName . ".tpl", $this->cacheKey );
}
function is_cached()
{
return $this->smarty->is_cached( $this->formTplName . ".tpl", $this->cacheKey );
}
}
class mvcController
{
function main()
{
switch( $this->page )
{
default:
$this->model = new mvcModel( $form );
$this->view = new mvcView( $this->model, "mvc-Index" );
if( $this->view->is_cached() == false )
{
$this->model->doSomethingHere();
}
break;
}
}
}
The beauty of this is that the model doesn’t need to know about the caching at all. The developer can concentrate on the business logic of his application without worrying about the underlying architecture. That’s one reason for keeping the cache key in the viewer too. Don’t lets confuse the developer!
Of course, this presumes the most simplistic caching system, but it would suffice for most cases!