2012-04-03 60 views
1

我已将我的网站(mysite.com)重定向到mysite.com/Mobile移动浏览器,使用默认控制器中的codeigniters useragent库。Codeigniter移动重定向与缓存

当我从控制器缓存输出时,重定向不起作用,因为浏览器被提供给缓存文件。

有没有适当的方式去从config/routes.php文件重定向?这会重定向移动访问者吗?

我控制器

类儿童扩展控制器{

function child() 
{ 
    parent::Controller(); 
    //$this->output->cache(7200); 
    $agent = $this->agent->browser() . ' ver ' . $this->agent->version(); 

} 

function index() 
{ 
    if ($this->agent->is_mobile()) 
    { 
     header('Location: ' . site_url() . 'Mobile/', TRUE, 301); 
     exit(0); 
    }else{ 
     $this->output->cache(7200); 
     $this->load->view('home',$data); 
    } 
} 

回答

2

使用CodeIgniter的输出缓存我不会建议。这在控制器之前运行,因此您将永远不会进入index()。路由无法处理这种情况,因为它无法检测到客户端是否是移动的。

使用CodeIgniter提供的其他缓存方法是一个更好的主意,因为它更细致,您可以缓存单个视图。 http://codeigniter.com/user_guide/libraries/caching.html

function index() 
{ 
    // should put this in the __construct() of this controller or in your MY_Controller.php 
    $this->load->driver('cache', array('adapter' => 'apc', 'backup' => 'file')); 

    if ($this->agent->is_mobile()) 
    { 
     redirect('Mobile'); 
    } 
    else 
    { 
     // if this doesn't get us the output, recreate and store it 
     if(!$output = $this->cache->get('controllername_index_output')) 
     { 
      $output = $this->load->view('home', $data, TRUE); 
      $this->cache->save('controllername_index_output', $output, 7200); 
     } 

     // now we surely have the output ready, whether it was cached or not 
     $this->output->set_output($output);   
    } 
} 
+0

感谢您的回复。它非常有意义。我仍然运行CI版本1.7。我看不到库下的缓存驱动程序。 CI 1.7中的缓存工作方式不同吗? – preschool 2012-04-04 21:06:57

+0

这种其他类型的缓存是在2.0中实现的。您需要手动使用APC/memcached来根据需要使用缓存。示例中的http://www.php.net/manual/en/function.apc-add.php与CodeIgniter函数的使用有一点不同。 – Woxxy 2012-04-05 11:19:33

+0

我升级到2.0,它的作品就像一个魅力! – preschool 2012-04-09 21:00:56