cakePHP project, orgazization of folders, pages, functions
Im new to cakePHP开发者_C百科, and Im wondering how a 'live' site does this.
I see 2 possibilities :
1) There is one controller with a bunch of pages (functions) in its (extended) AppController.
2) There are many controllers, each with a small number of pages (functions) in its (extended) AppController.
(You probably get my question already, but Im going to say it in another way too)
Should I put my contact page in a separate controller than my blog page? (I have a hunch the answer is yes.) Why?
You don't need to create a controller for everything. In fact, you shouldn't, because there are better ways around it. The more static pages you have, the more out of hand it can get.
For Static Pages
Copy pages_controller.php from the cake/libs/controller folder over to your app/controllers folder. Add the following piece of code to your display() action:
function display() {
...
$page = Inflector::slug($page);
if (method_exists($this, $page)) {
$this->$page();
}
$this->render(join('/', $path));
return;
}
Then, modify your routes.php file to add the various static pages:
Router::connect('/about', array('controller' => 'pages', 'action' => 'display', 'about'));
Router::connect('/contact', array('controller' => 'pages', 'action' => 'display', 'contact'));
Now, the contact form is a static page, but has some logic attached to it. So, you can head over to your PagesController and create an action specifically for this (or any other page that isn't merely static):
function contact() {
if (!empty($this->data)) {
...
}
}
Basically, the route directs your static page request to the PagesController's display()
action. The display action checks if a method of the same name exists. If it does, it executes that action and displays the pages/{page}.ctp view.
For Non-Static Pages, eg. Blog
Now, this definitely needs a model. In fact, multiple models (Post hasMany Comment, Post HABTM Tag). In order to manipulate and access these different models, it's better that you place the code into a separate controller.
A lot of people like to name their controllers based on their URLs. For example, they name their controller as BlogController if they want a URL such as /blog
.
A method that I prefer is using routing to get the URLs that I want, and keeping controllers named as per CakePHP conventions.
Eg. A PostsController would control the Post model and related models. But if I wanted the /blog
URL to display a list of all the posts, I would write a route to point it to /posts/index
.
Router::connect('/blog', array('controller' => 'posts', 'action' => 'index'));
You can have additional routes too. Example: /blog/2010/06/10/whats-in-a-post
to point to /posts/view/
.
Again, this is just an example of what's possible. In the end, you should stick to the methods that you think helps keep your code organized for both you and your team.
精彩评论