cakephp url modification: remove action and add slug inflector

倖福魔咒の 提交于 2019-12-06 19:47:39

Use Id and Named parameter...

On routes.php

define new routes as-

Router::connect('/posts/:id-:title',
    array('controller' => 'posts',
        'action' => 'view')
);

This new defined routes will match and parse all url containing id and title named parameter..

Important Note:: Do not define new routes after the end of routes.php. Try to define on the middle of the file..

On view

echo $this->Html->link('Hi',array(
    'controller' => 'posts',
    'action' => 'view',
    'id' => 4,
    'title' => Inflector::slug('the quick brown fox')
));

Well the solution provided above will fulfill your needs, but still after reading your question one thing comes into my mind... in your controller you are trying to read posts using title I mean this will slow down your system not recommended in programming so use id and increase one more column in your db table for slug(SEO title) which will be used for creating your post urls.

For example: 
Post title: This is a test post 
Create seo title for this as: this-is-a-test-post-123
Stor seo title in DB as <this-is-a-test-post>

See 123 is your posts ID now change your controller function to get data based on id ie.123, I hope you cn extract 123 from the sting easily...

Note: remember you have to think about this-is-a-123 string also because they also land in post having id 123.

Use below route for the above solution:

Router::connect('/posts/*', array('controller' => 'posts', 'action' => 'view'),array('pass' => array('title')));

Now in your controller:

You will get string "this-is-a-test-post-123" in $post_title

function view($post_title=null){   

           $temp = explode('-',$post_title);
           $posts_id= end($temp); 
           $lastKey = end(array_keys($temp));
           unset($temp[$lastKey]);
           $seoTitle = implode("-",$temp);
           //Now compare the above seoTitle with DB seo title for unique urls


}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!