访问默认的 CakePHP 站点时,它会将您带到“home.ctp”页面。
Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home'));
我想在那里添加一些元素(例如博客文章),所以我想我可以将其添加到 PagesController() 类中:
public function home() {
$this->set('blogposts', $this->Blogpost->find('all'));
}
但这不起作用。
那么:在主页(或任何其他页面)上添加类似内容的正确方法是什么
最佳答案
首选选项是为主页创建自定义路由,但您也可以覆盖 PagesController 的显示功能
选项 1:(首选方法)
Router::connect('/', array('controller' => 'mycontroller', 'action' => 'myaction'));
选项2
Router::connect('/', array('controller' => 'pages', 'action' => 'home'));
选项 3:
class PagesController {
function display()
{
// default controller code here
// your custom code here
}
}
在您看来,最后一个选项是使用 requestAction,但不推荐这样做,因为它有巨大的性能缺陷
选项 4:(不推荐)
$newsitems = $this->requestAction(array('controller' => 'newsitems', 'action' => 'getlatestnews', 'limit' => 10));
关于cakephp - 在 CakePHP 中为 "home" View 添加 Controller 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9757807/