Adding a Controller Function for the Home View in CakePHP
When you visit the CakePHP site, by default you are taken to the "home.ctp" page.
Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home'));
I want to add some elements there (like blog posts), so I thought I could just add this to the PagesController () class:
public function home() {
$this->set('blogposts', $this->Blogpost->find('all'));
}
But it doesn't work.
So: what is the correct way to add something like this on the home page (or any other page for that matter)
The preferred option is to create a custom route for the master page, but you can also override the PagesController display function
Option 1: (preferred method)
Router::connect('/', array('controller' => 'mycontroller', 'action' => 'myaction'));
Option 2
Router::connect('/', array('controller' => 'pages', 'action' => 'home'));
Option 3:
class PagesController {
function display()
{
// default controller code here
// your custom code here
}
}
The latter option uses requestAction in your view, but it is not recommended as it has a huge performance disadvantage.
Option 4: (not recommended)
$newsitems = $this->requestAction(array('controller' => 'newsitems', 'action' => 'getlatestnews', 'limit' => 10));
In fact, the action display
, home
is a parameter. Therefore your main method on the controller pages should call display, not at home. After that, create a view display.ctp
.
Link:
- Routing
To answer the original question:
$this->loadModel('Blogpost');
Ideally, the model should be named
$this->loadModel('Blogpost');