用动态占位符实现整页缓存的方法

I want to try create something like Zend's Server Pagecache. What I want to achieve is to store page output, so I guess it would be direct html, but with possibility to insert some dynamic data to page.

Output caching is a large subject. Do do it right, you need to think a bit on the design.

Here are 2 ways. The code sample is just for explanation, it's not a working solution.

  1. Block cache and dynamic composition. Probably the best way. Divide your page into several bloks. Each block should be generated by separate function/class. You can use Zend_Cache_Frontend_* objects to cache those blocks. Once Your application know what to display, in the controller You can compose the output using cached blocks and the dynamic parts.

    class CachedController extends Zend_Action_Controller
    {

    public function indexAction()
    {
        $this->_view->leftBlock = $this->leftBlock();
        $this->_view->rightBlock = $this->rightBlock();
    }

    protected function leftBlock()
    {
        // prepare left block, can use Zend_View if you like
        // use Zend_Cache to cache the block 
    }


    protected function rightBlock()
    {
        // prepare left block, can use Zend_View if you like
        // use Zend_Cache to cache the block
    }

    }
/* VIEW SCRIPT */
<html>
  <body>
    <div class="left">
      Left cached block here
      <?php echo $this->leftBlock; ?>
    </div>
    <div class="main">
      Do Your dynamic part here
    </div>
    <div class="right">
      Right cached block here
      <?php echo $this->rightBlock; ?>
    </div>
  </body>
</html>
  1. Whole page cache with substring substitution. If you do not wish do divide the page into blocks, You can cache whole page (Also using Zend_Cache_Frontend_*), and then use PHP str functions to substitute or insert the dynamic part. You will need to capture output of the View rather then having it sent by the framework automagically (refer to docs on how to change this).

You can always load dynamic data with ajax. example: if user logged and going to vote or something.