Cache layer for MVC - Model or controller?

Posted by Industrial on Stack Overflow See other posts from Stack Overflow or by Industrial
Published on 2010-05-26T17:41:46Z Indexed on 2010/05/26 18:01 UTC
Read the original article Hit count: 207

Hi everyone,

I am having some second thoughts about where to implement the caching part. Where is the most appropriate place to implement it, you think?

Inside every model, or in the controller?

Approach 1 (psuedo-code):

// mycontroller.php

MyController extends Controller_class {
   function index () {
        $data = $this->model->getData();
        echo $data;
   }
}

// myModel.php

MyModel extends Model_Class{
    function getData() {

        $data = memcached->get('data');

        if (!$data) {
            $query->SQL_QUERY("Do query!");
        }

        return $data;
    }  
}

Approach 2:

// mycontroller.php

MyController extends Controller_class {
   function index () {
        $dataArray = $this->memcached->getMulti('data','data2');

        foreach ($dataArray as $key) {
            if (!$key) {
                $data = $this->model->getData();
                $this->memcached->set($key, $data);
            }
        }

        echo $data;
   }
}

// myModel.php

MyModel extends Model_Class{
    function getData() {           
        $query->SQL_QUERY("Do query!");

        return $data;
    }  
}

Thoughts:

Approach 1:

  • No multiget/multi-set. If a high number of keys would be returned, overhead would be caused.

  • Easier to maintain, all database/cache handling is in each model

Approach 2:

  • Better performancewise - multiset/multiget is used

  • More code required

  • Harder to maintain

Tell me what you think!

© Stack Overflow or respective owner

Related posts about php

Related posts about Performance