Is there any way to route urls in cake without having the ID in the url?
So instead of www.mydomain.com/id/article-name I just want www.mydomain.com/article-name
I've been following this. http://book.cakephp.org/开发者_StackOverflowview/543/Passing-parameters-to-action
Sure. The only requirement for this is that there's enough unique information in the URL to pin down the article you want. If /article-name
is unique in your database, you can use it to find the specific record you want.
In config/routes.php:
// ... configure all normal routes first ...
Router::connect('/*', array('controller' => 'articles', 'action' => 'view'));
In controllers/articles_controller.php:
function view ($article_name) {
$article = $this->Article->find('first', array(
'conditions' => array('Article.name' => $article_name)
));
...
}
Be careful not to name your products like anything that could legitimately appear in the URL, so you don't run into conflicts. Does the URL http://example.com/pages
point to the product 'pages' or to array('controller' => 'pages', 'action' => 'index')
? For this purpose you'll also need to define your routes in routes.php
in a way that allows all your controllers to be accessible first, and only the undefined rest gets piped into your ArticlesController
. Look at the third parameter of Routes::connect
, which allows you to specify a RegEx filter you could use for this purpose.
You could do this:
// In routes.php
$rewrites = array();
$rewrites = am($rewrites, ClassRegistry::init('Article')->rewrites());
$rewrites = am($rewrites, ClassRegistry::init('AnotherModel')->rewrites());
$rewrites = am($rewrites, ClassRegistry::init('YetAnother')->rewrites());
foreach ($rewrites as $rewrite) {
Router::connect($rewrite[0], $rewrite[1], $rewrite[2]);
}
With deceze's method, you can only have one catch all. In this method, you can define a whole stack if you want.
This method is kind of hacky though, since you are querying the model from a config file.
精彩评论