I have a URL in my CakePHP application that looks like http://www.example.com/category/1. Where category is the name of an action in the Websites controller. I have removed the controller name, using the CakePHP Routes file. And 1 is the id of the Food category, whose records need to be fetched from the database.
But my client requires me to have the url as example.com/category/Food, 开发者_Go百科without the numeric id for better SEO.
My question is that can CakePHP Routes fetch the name of the category id from the database and show it in the url? If yes, then kindly guide me to achieve this, as I am badly stuck on this.
Any help will be greatly appreciated.
First create a field named category_url_title in categories tables. Then add the following routing
//Route dynamic pages
Router::connect(
'/categories/:category_url_title',
array('controller'=>'categories', 'action'=>'view'),
array(
'category_url_title' => '(?!add|view|delete\b)\b[a-zA-Z0-9_-]+',
'pass'=>array('category_url_title')
)
);
And view method in Categories controller will be something as bellow
function view($category_url_title=null) {
$category = $this->Category->find('first', array('conditions'=> array('Category.category_url_title'=>$category_url_title)));
$this->set(compact('category'));
}
Hope this will help you.
You could have something like this in your Routes:
Routes::connect('/category/*', array('controller' => 'categories', 'action' => 'view'));
Then in your categories_controller::view($catName), you check whether this holds true:
if($this->Category->hasAny(array('name' => $catName))) {
// your code here
} else {
// set message in the view saying category not found
}
There are many ways to tackle this, this is just one that I remember off hands.
精彩评论