2

I can cache controller actions in my CakePHP 2 application by using CacheHelper. And this helper provides me to select cache duration, "nocache" parts of page etc.

But is it possible to serve cached actions regarding to User agent of the visitor. For instance I plan to show cached page to crawlers/bots, but construct the page if visitor is not bot. I don't want to select which parts of the page will be cached / nocached. Taking the page as a whole.

4

1 回答 1

3

我认为这对你有用:

假设您使用的是最新版本的 cakephp 将其添加到您的 core.php 波纹管到您配置 Cache.check 的行

示例和代码:

/**
 * Enable cache checking.
 *
 * If set to true, for view caching you must still use the controller
 * public $cacheAction inside your controllers to define caching settings.
 * You can either set it controller-wide by setting public $cacheAction = true,
 * or in each action using $this->cacheAction = true.
 *
 */
    // Configure::write('Cache.check', true);
    $UAs = array(
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.101 Safari/537.11'
    );

    if (in_array(env('HTTP_USER_AGENT'), $UAs)) {
        define('USE_CACHE', '1 hour');
        Configure::write('Cache.check', true);
    } else {
        define('USE_CACHE', false);
        Configure::write('Cache.check', false);
    }

$UAs 是指机器人的用户代理

这是一个示例控制器,您可以使用它来测试代码:

<?php
App::uses('AppController', 'Controller');

class HomeController extends AppController {

    public $name = 'Home';

    public $uses = array();

    public $helpers = array(
        'Cache'
    );

    public $cacheAction = USE_CACHE;

    public function index() {}

}
于 2012-12-22T13:21:12.590 回答