开发者

MVC, how to organize caching parts of page and how to be with View?

开发者 https://www.devze.com 2022-12-22 11:11 出处:网络
Right now I\'m trying to create my own tiny MVC (just for practice and for understanding MVC pattern details). I\'d like to cache parts of p开发者_如何学JAVAages (dropdowns, lists etc.) and I don\'t k

Right now I'm trying to create my own tiny MVC (just for practice and for understanding MVC pattern details). I'd like to cache parts of p开发者_如何学JAVAages (dropdowns, lists etc.) and I don't know what is the best way to organize it.

Let's imagine that I have PostsController with method getPostDetailsShortly($post_id). This method could look like this...

public function getPostDetailsShortly($post_id) {

  if (!$post_id) return false;
  $content = $this->memcache->get("post" . $post_id); //Trying to get post details HTML from memcache

  if (!$content) { //Not fount in memcache

    $model = new PostsModel();
    $data = $model->getPostDetailsShortly($post_id);

    $this->view->assign('data', $data);

    ob_start();
    $this->view->render();
    $content = ob_get_contents(); //Getting view output into variable
    ob_end_clean();

    $this->memcache->set('post' . $post_id, $content, 1000); //Writing variable to memcache

  }

  return $content;

}

Now I should make this controller method be available from Views. Because I will use it inside of other pages, for example, for building related posts list.

What is the best practice of doing it? Maybe I'm wrong and there are some better methods to organize caching parts of pages?

PS:Sorry for my English, but I hope it is clear.

Thank you!


The idea behind MVC for those who may be reading this who don't know, is to separate the MODEL, VIEW, and CONTROLLER architecture of the site. I am most familiar with CakePHP MVC framework. So this answer will be based on my knowledge of MVC as it pertains to CakePHP.

Since the information you are providing needs to be provided to the view, I would suggest building it as an HTML helper. A Helper is designed to provide reusable code to the view. The Controller is the implementation of the logic behind the code (what to do with the data coming from the forms on the view, what views to call, asking the model for data, etc.).

Looking over the question you are speaking about caching these items. I think it is a good thing if you anticipate getting large amounts of traffic, but not really necessary otherwise. Having said that, it seems the question is more about the architecture than the caching. The current architecture seems sound, but I would move the functionality into a "component" which is accessible from all Controllers. This will allow you to call it from any controller where you need it, without having to call a specific controller every time.

0

精彩评论

暂无评论...
验证码 换一张
取 消