0

At the moment I'm using php and apc in my mvc based site, it's a custom built simple mvc so I'm trying to build it to fit my needs.

However I'm unsure where is the preferred location in which to handle caching?

I have two choices (I think) .. either do all caching in the various controllers which would mean objects were stored in the cache, or store returned data from queries in the cache inside the method:

Controller Example:

function showPage() {

    $pageOb = new Page();

    $key = md5('pageOb->getQuery()');

    if(!$data = apc_fetch($key)){

        $data = $pageOb->getQuery();
        apc_add($key, $data, 600);
    }

    require 'template.php';
}   

Method Example:

function getQuery(){

    $sql = "SELECT * FROM table";
    $key = md5('query'.$sql);

    if(!$data = apc_fetch($key)){   

        $core = Connect::getInstance();
        $stmt = $core->dbh->prepare($sql);
        $stmt->execute();
        $data = $stmt->fetchAll();
        apc_add($key, $data, 600);
    }

    return $data;
}
Dan
  • 11,914
  • 14
  • 49
  • 112

2 Answers2

2

It kinda depends on how you understand and implement the Model layer. This would be how I would write the cache-related code in the Service level objects:

$user = $this->domainObjectFactory->build('User');
$user->setId(42);

if ( !$this->cacheMapper->fetch('User', $user) )
{
    $mapper = $this->mapperFactory->build('User');
    $mapper->fetch($user);
}

If you do not understand the terms this comment (skip to "side notes") might help. It would take too long to repeat the whole thing again.

As I understand it, the cache itself is just a different form of storage. And thus it is just another part of Data Source Layer(where mappers, DAOs and similar structures come from).

Community
  • 1
  • 1
tereško
  • 58,060
  • 25
  • 98
  • 150
1

You shouldn't have data-model concerns bubbling up into your Controller. This principle is encapsulated in SRP: http://en.wikipedia.org/wiki/Single_responsibility_principle

Your second solution is better, but it would be improved by further abstracting the retrieval of data from the source of data. Here is a good reference article on the subject, although the language being used is different the patterns still hold: http://www.alachisoft.com/resources/articles/domain-objects-caching-pattern.html

gazarsgo
  • 104
  • 2
  • 12